jQuery: more than one handler for same event

后端 未结 8 1384
终归单人心
终归单人心 2020-11-27 03:14

What happens if I bind two event handlers to the same event for the same element?

For example:

var elem = $(\"...\")
elem.click(...);
elem.click(...)         


        
8条回答
  •  春和景丽
    2020-11-27 03:36

    Made it work successfully using the 2 methods: Stephan202's encapsulation and multiple event listeners. I have 3 search tabs, let's define their input text id's in an Array:

    var ids = new Array("searchtab1", "searchtab2", "searchtab3");
    

    When the content of searchtab1 changes, I want to update searchtab2 and searchtab3. Did it this way for encapsulation:

    for (var i in ids) {
        $("#" + ids[i]).change(function() {
            for (var j in ids) {
                if (this != ids[j]) {
                    $("#" + ids[j]).val($(this).val());
                }
            }
        });
    }
    

    Multiple event listeners:

    for (var i in ids) {
        for (var j in ids) {
            if (ids[i] != ids[j]) {
                $("#" + ids[i]).change(function() {
                    $("#" + ids[j]).val($(this).val());
                });
            }
        }
    }
    

    I like both methods, but the programmer chose encapsulation, however multiple event listeners worked also. We used Chrome to test it.

提交回复
热议问题