jQuery change event being called twice

こ雲淡風輕ζ 提交于 2019-11-26 21:06:32

问题


I have a form with some input and select boxes, each has class="myClass". I also have the following script:

$(document).ready(function() {
    $(".myClass").change(function() {
        alert('bla');
    })
});

I dont understand why after each change in select box or input box, this function is being called twice. What's wrong here?

Appreciate your help!


回答1:


All I can think of is that you used the same class on the form itself. if so, remove the myClass style from your form tag.

Corrected : http://jsfiddle.net/rY6Gq/1/

Faulty one with double alert: http://jsfiddle.net/rY6Gq/




回答2:


e.stopImmediatePropagation(); is what worked for me.

$(document).ready(function() {
    $(".myClass").change(function(e) {
        e.stopImmediatePropagation();
        alert('bla');
    })
});



回答3:


Its a bug, You'd add

$("#some_id").unbind('change');

before any change call




回答4:


if this occurred in IE, it may be this bug as it was for me: http://bugs.jquery.com/ticket/6593

updating to jQuery 1.7.1 worked for me.




回答5:


It happens when the same class or whatever attribute you are binding also has the same name parent or child. Obviously, when you change a child, parent also gets changed (its child changes). If they have the same class or attribute, it should fire twice. For example, in the following if you bind to "myClass", it will be called twice.

<div class="myclass">
<select class="myClass">   </select>
</div>



回答6:


It isn't: http://jsfiddle.net/nfcAS/




回答7:


The only one that worked for me was unbind before the change check.

 $(".select2Component").unbind(); 
    $(".select2Component").change(function() { 
         //code
    });



回答8:


Try debugging the code in Firebug rather than alerting. It may be loosing the focus and returning it is causing the appearance of two changes when there isn't two happening



来源:https://stackoverflow.com/questions/5464695/jquery-change-event-being-called-twice

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!