简体   繁体   English

.each仅适用于第一个选择框

[英].each only working on 1st selectbox

Basically, when trying to utilise the each function in jQuery I'm bumping into a problem which I can't seem to get past, 基本上,当尝试利用jQuery中的each函数时,我遇到了一个似乎无法解决的问题,

Here's the jQuery code I'm attempting to use : 这是我尝试使用的jQuery代码:

$('#status_update').each(function(index) {
        alert(this);
        $(this).on('change', function (e) {
            alert('changed');
        });
});

Here's the HTML code I'm using : 这是我正在使用的HTML代码:

<select name='status_update[]' class='input input-medium' id='status_update' data-id='1'>
    <option value='0' selected>Not Admitted</option>
    <option value='1'>Admitted</option>
</select>

<select name='status_update[]' class='input input-medium' id='status_update' data-id='1'>
    <option value='0' selected>Not Admitted</option>
    <option value='1'>Admitted</option>
</select>
<select name='status_update[]' class='input input-medium' id='status_update' data-id='1'>
    <option value='0' selected>Not Admitted</option>
    <option value='1'>Admitted</option>
</select>

etc....

It works for the first one, but after that it doesn't activate the on.change() in the jQuery which results in it not processing. 它适用于第一个,但是此后它不会激活jQuery中的on.change() ,这导致它无法处理。

id should be unique in a document , you have multiple element with the same id. id在文档中应该是唯一的 ,您有多个具有相同id的元素。

You can use a common class for all the element and use the class selector instead of id selector 您可以对所有元素使用通用类,并使用类选择器代替id选择器

$('.status_update').each(function(index) {
        alert(this);
        $(this).on('change', function (e) {
            alert('changed');
        });
});

An ID should only be applied to a single element. ID仅应应用于单个元素。 Try using .input-medium as your jquery selector, ie: 尝试使用.input-medium作为您的jquery选择器,即:

$('.input-medium').each(function(index) {
    alert(this);
    $(this).on('change', function (e) {
        alert('changed');
    });
});

您不能为多个元素分配相同的ID,因此最好删除ID并使用类

If elements are dynamically generated, there are two workaround to this: 如果元素是动态生成的,则有两种解决方法:

First: use jQuery live function [deprecated], use jQuery on instead 第一:使用jQuery live函数[不建议使用],改为使用jQuery

http://api.jquery.com/on/ http://api.jquery.com/on/

Second: upon creation of the element, add the onchange with it. 第二:创建元素后,添加onchange。 example: 例:

val jQel = $("<select name='status_update[]' class='input input-medium' data-id='1'>
    <option value='0' selected>Not Admitted</option>
    <option value='1'>Admitted</option>
</select>");
$(jQel).find(".input").change(function(){
 //add code here
});
//then your append code somewhere

Try this 尝试这个

$('input[id="status_update"]').each(function(index) {
        alert(this);
        $(this).on('change', function (e) {
            alert('changed');
        });
});

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

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