Can I have two JavaScript onclick events in one element?

后端 未结 5 623
南旧
南旧 2020-12-13 10:00

Can we put two JavaScript onclick events in one input type button tag? To call two different functions?

5条回答
  •  没有蜡笔的小新
    2020-12-13 10:52

    The HTML

    click
    

    And the javascript

    // get a cross-browser function for adding events, place this in [global] or somewhere you can access it
    var on = (function(){
        if (window.addEventListener) {
            return function(target, type, listener){
                target.addEventListener(type, listener, false);
            };
        }
        else {
            return function(object, sEvent, fpNotify){
                object.attachEvent("on" + sEvent, fpNotify);
            };
        }
    }());
    
    // find the element
    var el = document.getElementById("btn");
    
    // add the first listener
    on(el, "click", function(){
        alert("foo");
    });
    
    // add the second listener
    on(el, "click", function(){
        alert("bar");
    });
    

    This will alert both 'foo' and 'bar' when clicked.

提交回复
热议问题