How to change onClick handler dynamically?

前端 未结 11 1439
清歌不尽
清歌不尽 2020-12-02 15:37

I\'m sure there are a million posts about this out there, but surprisingly I\'m having trouble finding something.

I have a simple script where I want to set the onC

相关标签:
11条回答
  • 2020-12-02 16:00

    The YUI example above should really be:

    <script>
      YAHOO.util.Event.onDOMReady(function() {   
         Dom.get("foo").onclick =  function (){alert('foo');};
      });
    </script>
    
    0 讨论(0)
  • 2020-12-02 16:01

    Use .onclick (all lowercase). Like so:

    document.getElementById("foo").onclick = function () {
      alert('foo'); // do your stuff
      return false; // <-- to suppress the default link behaviour
    };
    

    Actually, you'll probably find yourself way better off using some good library (I recommend jQuery for several reasons) to get you up and running, and writing clean javascript.

    Cross-browser (in)compatibilities are a right hell to deal with for anyone - let alone someone who's just starting.

    0 讨论(0)
  • 2020-12-02 16:03

    I agree that using jQuery is the best option. You should also avoid using body's onload function and use jQuery's ready function instead. As for the event listeners, they should be functions that take one argument:

    document.getElementById("foo").onclick = function (event){alert('foo');};
    

    or in jQuery:

    $('#foo').click(function(event) { alert('foo'); }
    
    0 讨论(0)
  • 2020-12-02 16:11

    I think you want to use jQuery's .bind and .unBind methods. In my testing, changing the click event using .click and .onclick actually called the newly assigned event, resulting in a never-ending loop.

    For example, if the events you are toggling between are hide() and unHide(), and clicking one switches the click event to the other, you would end up in a continuous loop. A better way would be to do this:

    $(element).unbind().bind( 'click' , function(){ alert('!') } ); 
    
    0 讨论(0)
  • 2020-12-02 16:12

    jQuery:

    $('#foo').click(function() { alert('foo'); });
    

    Or if you don't want it to follow the link href:

    $('#foo').click(function() { alert('foo'); return false; });
    
    0 讨论(0)
提交回复
热议问题