开发者

why would this jquery live enter an infinite loop, where an almost identical one does not?

I'm trying to have a form where the values are updated based on changes in either a select, or changes in a text field.

I started with

jQuery('select[name=measure]','form').live('change',function(){
 alert('triggered');
});

I then added the keyup for when the user alters a text box

jQuery('select[name=measure],input[name=amount]','form').live('change keyup',function(){
  alert('triggered');
});

For some reason this enters an infinite loop when 开发者_开发知识库I select an option, and is triggered multiple times on keyup (though not infinitely).

When I change to

...live('keyup', function()...

changes to the text-box are only triggered once. I could split them into two seperate .live events and then create a separate function, but that doesn't seem to be efficient code.


It's attaching the change and keyup to select[name=measure] and input[name=amount].

I doubt you want the input to have a change event and the select to have a keyup event.

I recommend you separate these two live events. You probably don't need the form selector either.

$('select[name=measure]').live('change', SomeFunction);

$('input[name=amount]').live('keyup', SomeFunction);

function SomeFunction() {
    // this isn't inefficient
}

working example: http://jsfiddle.net/K7586/


or you could use delegate()

$("form")
    .delegate("input[name=amount]", "keyup", SomeFunction)
    .delegate("select[name=measure]", "change", SomeFunction);

function SomeFunction() {
    // this isn't inefficient
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜