Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
228 views
in Technique[技术] by (71.8m points)

Is it possible to trigger a link's (or any element's) click event through JavaScript?

I'm writing some JavaScript code that needs to fire the click event for a link. In Internet Explorer I can do this

var button = document.getElementById('myButton');
button.click();

But this doesn't work in Firefox, and I assume any other browser. In Firefox, I've done this

var button = document.getElementById('myButton');
window.location = button.href;

I feel like this is not the best way to do this. Is there a better way to trigger a click event? Preferably something that works regardless of the type of element or the browser.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

http://jehiah.cz/archive/firing-javascript-events-properly

function fireEvent(element,event) {
   if (document.createEvent) {
       // dispatch for firefox + others
       var evt = document.createEvent("HTMLEvents");
       evt.initEvent(event, true, true ); // event type,bubbling,cancelable
       return !element.dispatchEvent(evt);
   } else {
       // dispatch for IE
       var evt = document.createEventObject();
       return element.fireEvent('on'+event,evt)
   }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...