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 bot开发者_运维技巧h in firefox and Internet Explorer
Thanks
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();
精彩评论