尝试使用 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()
在:选择 option
:
$("#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});
}
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句