我需要从数组中获得所选选项的相关值。
我的选择:
<select id="BestMobileSelect">
<option></option>
<option value=Mobile-SmartPhone-Motorola>Motorola</option>
<option value=Mobile-SmartPhone-Samsung>Samsung</option>
<option value=Mobile-SmartPhone-Xiaomi>Xiaomi</option>
</select>
数组:
var BestMobileJSON = {
"Mobile-SmartPhone-Motorola" : [{"Price":"Rs.12000"}],
"Mobile-SmartPhone-Samsung" : [{"Price":"Rs.15000"}],
"Mobile-SmartPhone-Xiaomi" : [{"Price":"Rs.9000"}],
}
我使用的jquery获得相关的值如下:
$("#BestMobileSelect").on("change", function () {
var BestMobileSelected = $(this).val()
var markup = '';
jQuery.each(BestMobileSelected, function(index, value){
markup += '<div>' + BestMobileJSON[value][0].Price +'</div>'
});
$("#BestMobileResult").html(markup);
});
然而,这是不工作,我得到错误Uncaught TypeError: Cannot use 'in' operator to search for 'length' in Mobile-SmartPhone-Motorola
为什么不工作?
找到下面的完整代码:
jQuery(document).ready(function($) {
var BestMobileJSON = {
"Mobile-SmartPhone-Motorola": [{
"Price": "Rs.12000"
}],
"Mobile-SmartPhone-Samsung": [{
"Price": "Rs.15000"
}],
"Mobile-SmartPhone-Xiaomi": [{
"Price": "Rs.9000"
}],
}
$("#BestMobileSelect").on("change", function() {
var BestMobileSelected = $(this).val()
var markup = '';
jQuery.each(BestMobileSelected, function(index, value) {
markup += '<div>' + BestMobileJSON[value][0].Price + '</div>'
});
$("#BestMobileResult").html(markup);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<select id="BestMobileSelect">
<option></option>
<option value=Mobile-SmartPhone-Motorola>Motorola</option>
<option value=Mobile-SmartPhone-Samsung>Samsung</option>
<option value=Mobile-SmartPhone-Xiaomi>Xiaomi</option>
</select>
<div id="BestMobileResult"></div>
$.each()
的参数必须是数组或对象,但BestMobileSelected
是字符串。您应该使用下拉值作为BestMobileJSON
对象的索引;这将返回一个数组,然后您可以使用$.each()
遍历该数组。
jQuery(document).ready(function($) {
var BestMobileJSON = {
"Mobile-SmartPhone-Motorola": [{
"Price": "Rs.12000"
}],
"Mobile-SmartPhone-Samsung": [{
"Price": "Rs.15000"
}],
"Mobile-SmartPhone-Xiaomi": [{
"Price": "Rs.9000"
}],
}
$("#BestMobileSelect").on("change", function() {
var markup = '';
let val = $(this).val();
if (val) {
var BestMobileSelected = BestMobileJSON[val];
jQuery.each(BestMobileSelected, function(index, value) {
markup += '<div>' + value.Price + '</div>'
});
}
$("#BestMobileResult").html(markup);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<select id="BestMobileSelect">
<option></option>
<option value=Mobile-SmartPhone-Motorola>Motorola</option>
<option value=Mobile-SmartPhone-Samsung>Samsung</option>
<option value=Mobile-SmartPhone-Xiaomi>Xiaomi</option>
</select>
<div id="BestMobileResult"></div>