简体   繁体   English

将更改侦听器附加到jquery选择的循环中,无法正常工作

[英]Attaching change listener to the jquery-chosen selects in a loop, not working

I am trying to init multiple chosen select in a loop: 我试图在循环中初始化多个选择的选择:

var arr = ["#key1", "#key2"];

for (var p in arr) {
    $(arr[p]).chosen().change(function () {
        console.log($(arr[p]).chosen().val());
    });
}

where the elements are: 元素在哪里:

<div>
    <select multiple="" id="key1">
        <option value="A1">A1</option>
        <option value="B1">B1</option>
    </select>
</div>
<div>
    <select multiple="" id="key2">
        <option value="A2">A2</option>
        <option value="B2">B2</option>
    </select>
</div>

The problem is, the last 'change' event handler is getting attached to all select elements. 问题是, 最后一个 “更改”事件处理程序已附加到所有选择元素。 For example, selecting an item from "key1" prints null since the .chosen().val() is getting the values from "key2". 例如,由于.chosen().val()从“ key2”中获取值,因此从“ key1”中选择一个项目将输出null Any suggestions? 有什么建议么?

Actually I wanted to store the selected values of each chosen into different fields, for instance, into of this object: 实际上,我想将每个选定值的选定值存储到此对象的不同字段中,例如:

var selected_values = {
    selected_keys1 : {},
    selected_keys2 : {}
}

You don't need a loop to do this. 您不需要循环即可执行此操作。 You can retrieve both elements by separating the id selector with a comma. 您可以通过用逗号分隔id选择器来检索这两个元素。 In the change handler you can then reference the element that raised the event using the this keyword. 然后,您可以在change处理程序中使用this关键字引用引发事件的元素。 Try this: 尝试这个:

$("#key1, #key2").chosen().change(function () {
    console.log($(this).val());
});

Example fiddle 小提琴的例子

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM