Can I have two JavaScript onclick events in one element?

后端 未结 5 605
南旧
南旧 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:39

    This one works:

    <input type="button" value="test" onclick="alert('hey'); alert('ho');" />

    And this one too:

    function Hey()
    {
        alert('hey');
    }
    
    function Ho()
    {
        alert('ho');
    }
    

    .

    <input type="button" value="test" onclick="Hey(); Ho();" />
    

    So the answer is - yes you can :) However, I'd recommend to use unobtrusive JavaScript.. mixing js with HTML is just nasty.

    0 讨论(0)
  • 2020-12-13 10:52

    The HTML

    <a href="#" id="btn">click</a>
    

    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.

    0 讨论(0)
  • 2020-12-13 10:54

    You could try something like this as well

    <a href="#" onclick="one(); two();" >click</a>
    
    <script type="text/javascript">
        function one(){
            alert('test');
        }
    
        function two(){
            alert('test2');
        }
    </script>
    
    0 讨论(0)
  • 2020-12-13 11:00

    You can attach a handler which would call as many others as you like:

    <a href="#blah" id="myLink"/>
    
    <script type="text/javascript">
    
    function myOtherFunction() {
    //do stuff...
    }
    
    document.getElementById( 'myLink' ).onclick = function() {
       //do stuff...
       myOtherFunction();
    };
    
    </script>
    
    0 讨论(0)
  • 2020-12-13 11:03

    There is no need to have two functions within one element, you need just one that calls the other two!

    HTML

    <a href="#" onclick="my_func()" >click</a>
    

    JavaScript

    function my_func() {
        my_func_1();
        my_func_2();
    }
    
    0 讨论(0)
提交回复
热议问题