我有两个选择框:
<select class="company">
<option value=''><strong>Name</strong></option>
<option value="Company A">Company A</option>
<option value="Company B">Company B</option>
</select>
<select class="product">
<option value=''><strong>Products</strong></option>
</select>
我需要根据两个选择框选择从数组中获取位置值。它将用于另一个功能。这是我的剧本:
var series = [
{name: 'Company A', product: 'A1',location:'USA'},
{name: 'Company A', product: 'A2',location:'Mexico'},
{name: 'Company A', product: 'A3',location:'China'},
{name: 'Company B', product: 'B1',location:'USA'},
{name: 'Company B', product: 'B2',location:'Mexico'}
]
$(".company").change(function(){
var company = $(this).val();
var options = '<option value=""><strong>Products</strong></option>';
$(series).each(function(index, value){
if(value.name == company){
options += '<option value="'+value.product+'">'+value.product+'</option>';
}
});
$('.product').html(options);
});
我也希望将名称和产品存储在一个变量中,但这只是为了表明它从数组中选择了正确的值,它不会在其他任何地方使用
答案 0 :(得分:3)
我将在html中使用helper data
属性!使用data
也很容易获得!在这里,我尝试使用data-location
属性...
var series = [
{name: 'Company A', product: 'A1',location:'USA'},
{name: 'Company A', product: 'A2',location:'Mexico'},
{name: 'Company A', product: 'A3',location:'China'},
{name: 'Company B', product: 'B1',location:'USA'},
{name: 'Company B', product: 'B2',location:'Mexico'}
]
$(".company").change(function(){
var company = $(this).val();
var options = '<option value=""><strong>Products</strong></option>';
$(series).each(function(index, value){
if(value.name == company){
options += '<option value="'+value.product+'" data-location="'+value.location+'">'+value.product+'</option>';
}
});
$('.product').html(options).off().on("change",function(){
console.log($(this).find(":selected").data("location"));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="company">
<option value=''><strong>Name</strong></option>
<option value="Company A">Company A</option>
<option value="Company B">Company B</option>
</select>
<select class="product">
<option value=''><strong>Products</strong></option>
</select>
答案 1 :(得分:0)
let name = ...
let product = ...
let result = (series.find((item) => {
return (item.name === name) && (item.product===product)
})).location;
使用jquery获取名称和产品的值