嗨,我正在尝试将这些对象在javascript中定义为单独的变量,但我不成功,如何将这些值分开,例如,login =“ uk”和另一个用于review =“ com”的变量
<label for="location">Country</label>
<select name="location" id="location" value="" >
<option value=""></option>
<option value='{"login":"uk","review":"com"}'>UK</option>
<option value='{"login":"Canada","review":"ca"}'> Canada</option>
</select>
最佳答案
使用JQuery,您可以执行以下操作:
var login, review;
$("#location").on("change", function(){
var obj = JSON.parse($(this).val());
login = obj.login;
review = obj.review;
});
var login, review;
$("#location").on("change", function(){
var obj = JSON.parse($(this).val());
login = obj.login;
review = obj.review;
console.log(review);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label for="location">Country</label>
<select name="location" id="location" value="" >
<option value=""></option>
<option value='{"login":"uk","review":"com"}'>UK</option>
<option value='{"login":"Canada","review":"ca"}'> Canada</option>
</select>