我有一个包含 optgroup 的选择框。我需要向其中添加一个事件监听器,例如 onclick 或 onchange,它们将触发事件,但仅当我向其中添加新选项时才有效。
以下是我的选择方法:
var $selectedExam = $("#formExam_released"); //this is the <optgroup>
我试过了
$selectedExam.on("change", function(){
removeDuplicates('exam');
});
但只有当我单击 optgroup 中的某个项目时,才会触发“removeDuplicates”。
有什么想法吗?
最佳答案
类似这样的吗?
$().ready(function() {
$("optgroup").each(function() {
$(this).on("change", function() {
var id = $(this).attr(id);
var arrrayOfElements = [];
$("optgroup").each(function() {
if($(this).attr("id") == id) {
$(this + " option").each(function() {
arrrayOfElements[arrrayOfElements.length] = $(this).val();
});
}
});
for (var i = 0; i < arrrayOfElements.length; i++) {
for(var j = 0; j < arrrayOfElements.length; j++) {
if(arrrayOfElements[i] == arrrayOfElements[j]) {
$("optgroup option[value='"+ arrrayOfElements[i] +"']").each(function() {
$(this).remove();
});
}
}
}
});
});
});
此代码应从选择选项中删除所有重复项。这可以在 .on("change",...);
编辑后,只要添加具有唯一标识符的属性ID,就可以搜索到该值。
关于javascript - JQuery 添加到 optgroup 触发事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25858148/