Fake “click” to activate an onclick method

前端 未结 11 697
醉话见心
醉话见心 2020-11-28 10:11

I have an element with an onclick method.

I would like to activate that method (or: fake a click on this element) within another function.

I

相关标签:
11条回答
  • 2020-11-28 10:51

    If you're using JQuery you can do:

    $('#elementid').click();
    
    0 讨论(0)
  • 2020-11-28 10:51

    I haven't used jQuery, but IIRC, the first method mentioned doesn't trigger the onclick handler.

    I'd call the associated onclick method directly, if you're not using the event details.

    0 讨论(0)
  • 2020-11-28 10:58
    var clickEvent = new MouseEvent('click', {
      view: window,
      bubbles: true,
      cancelable: true
    });
    var element = document.getElementById('element-id'); 
    var cancelled = !element.dispatchEvent(clickEvent);
    if (cancelled) {
      // A handler called preventDefault.
      alert("cancelled");
    } else {
      // None of the handlers called preventDefault.
      alert("not cancelled");
    }
    

    element.dispatchEvent is supported in all major browsers. The example above is based on an sample simulateClick() function on MDN.

    0 讨论(0)
  • 2020-11-28 11:01

    For IE there is fireEvent() method. Don't know if that works for other browsers.

    0 讨论(0)
  • 2020-11-28 11:07

    Once you have selected an element you can call click()

    document.getElementById('link').click();
    

    see: https://developer.mozilla.org/En/DOM/Element.click

    I don't remember if this works on IE, but it should. I don't have a windows machine nearby.

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