我有这个 HTML 表单:
<form id="form">
<select name="from" id="from" class="form-control">
<option value=""></option>
</select>
<select name="to" id="to" class="form-control">
<option value=""></option>
</select>
<button type="button" id="but">Click Me!</button>
</form>
单击按钮后,我运行此 jquery 脚本
$( document ).ready(function() {
var from = $('#from').val();
var to = $('#to').val();
//Object 1
var obj1 = {
from: "x", to: "y"
};
//Object 2
var obj2 = {
from: "x", to: "z"
};
//Object 3
var obj3 = {
from: "y", to: "z"
};
//Array
var a=[];
//Put objects in array
a.push(obj1, obj2, obj3);
for (i = 0; i < a.length; ++i){
if (a[i].from) {
// Inserts two x's
$('#from').append( $('<option></option>').val(a[i].from).html(a[i].from) );
}
}
//On click
$('#but').on('click', function(e){
var from = $('#from').val();
for (i = 0; i < a.length; ++i) {
if (from == a[i].from) {
//Update once the #to values
$('#to').append( $('<option></option>').val(a[i].to).html(a[i].to) );
}
}
});
});
我的问题是,我试图将数组值作为选项放入 html 中的选择字段中,并且我希望它们是唯一的。
前两个选项是:从 x 到 y 和从 x 到 z,它在 #from 值中返回两个 x。
是否有一种方法可以显示一个 x 以及所有将 x 作为 #from 的 #to 值?
最佳答案
你可以尝试这样的事情:
var a = [];
var fromExists = [];
a.push(obj1, obj2, obj3);
for (i = 0; i < a.length; ++i){
if (a[i].from && fromExists.indexOf(a[i].from) === -1) {
fromExists.push(a[i].from);
// Inserts two x's
$('#from').append( $('<option></option>').val(a[i].from).html(a[i].from) );
}
}
关于javascript - jquery 从数组选择选项 - 重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42510341/