Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

yui - Javascript: simulate a click on a link

I have a link that has a listener attached to it (I'm using YUI):

YAHOO.util.Event.on(Element, 'click', function(){ /* some functionality */});

I would like to the same functionality to happen in another scenario that doesn't involve a user-click. Ideally I could just simulate "clicking" on the Element and have the functionality automatically fire. How could I do this? Too bad this doesn't work:

$('Element').click()

Thanks.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

MDC has a good example of using dispatchEvent to simulate click events.

Here is some code to simulate a click on an element that also checks if something canceled the event:

function simulateClick(elm) {
  var evt = document.createEvent("MouseEvents");
  evt.initMouseEvent("click", true, true, window,
    0, 0, 0, 0, 0, false, false, false, false, 0, null);
  var canceled = !elm.dispatchEvent(evt);
  if(canceled) {
    // A handler called preventDefault
    // uh-oh, did some XSS hack your site?
  } else {
    // None of the handlers called preventDefault
    // do stuff
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...