admin管理员组

文章数量:1399972

I would like to click a link in my page using javascript. I would like to Fire event handlers on the link without navigating. How can this be done? This has to work both in firefox and Internet Explorer

Thanks

I would like to click a link in my page using javascript. I would like to Fire event handlers on the link without navigating. How can this be done? This has to work both in firefox and Internet Explorer

Thanks

Share Improve this question asked Nov 13, 2009 at 4:03 user189598user189598 2
  • 1 You asked this already: stackoverflow./questions/1722863/… – Crescent Fresh Commented Nov 13, 2009 at 9:33
  • Damn it where'd that answer just go.... Was trying to ment. – Roatin Marth Commented Nov 13, 2009 at 14:27
Add a ment  | 

2 Answers 2

Reset to default 4

With plain JavaScript it depends on how do you bind the event, if you assigned an anonymous function to the onclick attribute of the element, you can simply:

var link = document.getElementById('linkId');
link.onclick();

If you used addEventListener or attachEvent (for IE) you should simulate the event, using the DOM Level 2 Standard document.createEvent or element.fireEvent (for IE).

For example:

function simulateClick(el) {
  var evt;
  if (document.createEvent) { // DOM Level 2 standard
    evt = document.createEvent("MouseEvents");
    evt.initMouseEvent("click", true, true, window,
      0, 0, 0, 0, 0, false, false, false, false, 0, null);

    el.dispatchEvent(evt);
  } else if (el.fireEvent) { // IE
    el.fireEvent('onclick');
  }
}

Check the above example here.

If you use jQuery...

$('a#myLinkID').click();

本文标签: How to fire event handlers on the link using javascriptStack Overflow