Javascript click function

前端 未结 4 1305
猫巷女王i
猫巷女王i 2020-12-21 07:10

I\'ve got some code which works fine in IE but unfortunately not in Google Chrome/Firefox.

It relies upon calling a click() event on a button from javascript. Readin

相关标签:
4条回答
  • 2020-12-21 07:21

    onclick="methodcall();" works for me fine...

    0 讨论(0)
  • 2020-12-21 07:32

    I think you're looking for element.dispatchEvent:

    function simulateClick() {
      var evt = document.createEvent("MouseEvents");
      evt.initMouseEvent("click", true, true, window,
        0, 0, 0, 0, 0, false, false, false, false, 0, null);
      var cb = document.getElementById("checkbox"); 
      var canceled = !cb.dispatchEvent(evt);
      if(canceled) {
        // A handler called preventDefault
        alert("canceled");
      } else {
        // None of the handlers called preventDefault
        alert("not canceled");
      }
    }
    

    I read your question as "I'm trying to fire the onclick event for my button", whereas everyone else seems to have read it as "I'm trying to handle an onclick event for my button". Please let me know if I've got this wrong.

    Modifying your code, a proper x-browser implementation might be:

    if (linkButton != null) 
    { 
      if (linkButton.fireEvent) 
        linkButton.fireEvent("onclick"); 
      else 
      { 
        var evt = document.createEvent("MouseEvents");
        evt.initMouseEvent("click", true, true, window,
                                   0, 0, 0, 0, 0, false, false, false, false, 0, null);
        linkButton.dispatchEvent(evt);
      } 
    } 
    
    0 讨论(0)
  • 2020-12-21 07:35

    you can use onClick attribute or if you need more functionality have a look at jQuery and events it offers: http://api.jquery.com/category/events/

    0 讨论(0)
  • 2020-12-21 07:38

    onclick attribute should be crossbrowser:

    <input type="button" onclick="something()" value="" />
    

    EDIT

    And there was this question that seems to be about the same problem: setAttribute, onClick and cross browser compatibility

    0 讨论(0)
提交回复
热议问题