尝试使用 jquery 在选定选项的数组中查找数据值,找到它时,我想添加一个属性,因为它们是一个选项标签,一个选定的属性。
这看起来很容易,但实际上并非如此。
我的代码如下:
function selected_element() {
var association = $("#association").children("option").map(function() {
return this.value;
}).get();
var ass_val = $("#association").children("option");
console.log(ass_val, association);
var ass_data = $("#association").children("option").attr('data-selected');
console.log(ass_data );
if (ass_val == ass_data) {
$("#association").children("option").val(ass_data).attr("selected","selected");
}
};
selected_element();
这只是一个例子:
我的第一行将映射我的数组,所以我返回值 (1,2,3,4(。
我的第二行将返回选项和值,但我不能用它们做很多事情。
在这种情况下,我的ass_data实际上是我用来检索数据标记的数组(数据选择(。
我的最后一行代码只是我希望实现的目标的一个例子:
if (ass_val == ass_data) {
$("#association").children("option").val(ass_data).attr("selected","selected");
}
};
这行不通,只是为了展示我的想法。
假设这些值是唯一的,您只需为下拉列表添加一个事件侦听器,然后find()
:selectedoption
:
$("#association").on("change", function () {
var t = $(this),
val = t.val();
if (val) { // filter out empty/null values as possible matches
t.find(":selected").attr({<put attribute name here> : <attribute value here>});
// for example
// t.find(":selected").attr({"data-selected" : true});
}
});