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
502 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 Answer

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
  }
}

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

...