1

I am binding 3 events:

$("#form").bind('keyup change submit',function(event){
    //do something
    alert("test alert");
});

In a form you can have text fields, dropdowns, checkboxes, etc....

From what I noticed, the "change" event does not get triggered with text fields until you click 'outside' of the text box. So, I use the "keyup" event, which works great for me.
And the "submit" event is self explanatory. (I'm basically saving myself from doing multiple selectors by binding these events.) And I may want to add more events later.

Here is my problem....

The popup alert will trigger 2x, when I make a change to a textbox. Not sure if that's because I am clicking the button on the popup that causes it, or if changing the value in the textbox can also trigger both the keyup & change events at the same time.

Either way, it's driving me nuts.

Any thoughts on improving this method, without having multiple selectors?

4

3 回答 3

1

编辑:我刚刚看到您关于“没有多个选择器”的注释。如果需要,可以将以下内容链接起来,如果这符合要求的话。

为了最有效地使用内存,我会将其分解为几个语句。

//Your function
var handler = function(e) {  alert('blah'); };

$('#form input[type=text], #form textarea').keyup(handler);
$('#form select, #form checkbox, #form radio').change(handler);
$('#form').submit(handler);

这很好,因为元素只触发一个事件,它可以帮助你。

附带说明一下,如果您期望 IE 6 支持,则在复选框/收音机/选择模糊之前不会触发更改事件,因此您可能希望以不同的方式处理这些(单击仍然适用于复选框/收音机)。

于 2009-11-08T18:46:02.797 回答
0

Why don't you set a Boolean flag somewhere outside of the callback functions (still in a shared scope of course). The first call will set the flag and execute, the others will see the flag and return. You can reset the flag when the user closes the alert box.

EDIT: Another option if you still want different elements to be able to issue these alerts is have the handler remove itself as an event listener. Then you could re register it when the alert box closes.

于 2009-11-08T00:27:23.167 回答
0

第二个警报由第一个警报触发。当第一个警报弹出时,文本字段失去焦点并触发更改事件。如果您真正的处理程序不会导致文本字段失去焦点,那应该不是问题。但是,您可能希望忽略文本字段中的更改事件,因为您已经在使用 keyup 来处理这些字段。
使用 Ryan Lynch 的标志想法,您可以执行以下操作:

var target = null;
$("#form").bind('keyup change submit',function(event){
    if (event.type == 'keyup') {
        target = event.target;
    // a change event after one or more keyup events in the same element
    } else if (event.type == 'change' && target === event.target) {
        //do nothing
        return false;
    }
    // actual handler code
    alert(event.type) // test code
});

在火狐上测试。我希望这有帮助。

于 2009-11-08T04:50:46.783 回答