Just-Blog, 就是Blog

如何用 JavaScript 觸發 Event

by 連小峰 on 六月.21, 2007, under 電腦三兩事

舉例來說,如果我想在程式中利用程式去按某個按鈕,並觸發它的 onClick 事件,該怎麼做?

方法如下:

 el = getElementById(『buttonID』);
 if (navigator.appVersion.match(/\bMSIE\b/)){
  el.click();
 }else{
  var evt = document.createEvent(『MouseEvents』);
  evt.initEvent(『click』, true, true);
  el.dispatchEvent(evt);
 }

因為在 IE 與在 netscape(mozilla) 用來觸發 Event 的命令並不一樣,所以要先做判斷,做不同的處理。


1 Comment for this entry

Leave a Reply

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Visit our friends!

A few highly recommended friends...