开发者

is it possible to manually call a click on a dom object?

I am using addthis and they have a bunch of obfuscated code that I am loathe to dig through in their embedded javascript. I would like to "click" one of their buttons on my page without the user having to touch it.

So, in essence, there is a <a> that contains their button (which their embedded javascript handles when th开发者_Python百科e user clicks it). I would like to "click" it for them, via my own javascript, but don't see anything like a native "clickMe()" function associated with the anchor tag object.

Is it possible to do this, or is it missing from the spec due to security concerns?


I looked at the AddThis code more carefully and their functionality is have an onclick handler for the parent div of each a. If you know the id of the div you want to click, just put it in this line. As a back up, you can also try click() for the a.

var id = 'atic_facebook'; //for example
document.getElementById(id).onclick();


This is a function to programmatically fire an event on a DOM element:

function eventFire(el, etype){
   if (el.fireEvent) {
     (el.fireEvent('on' + etype));
   } else {
     var evObj = document.createEvent('Events');
     evObj.initEvent(etype, true, false);
     el.dispatchEvent(evObj);
   }
}
// usage
eventFire(document.getElementById('someHref'),'click');
eventFire(document.getElementById('someElement'),'mouseover');
// etc.


You can call the "onclick" function of an element directly:

var as = document.getElementsByTagName('a'), i;
for (i=0; i<as.length; i++) {
  if (as[i].onclick) {
    as[i].onclick(); // Run the "onclick" function.
  } else if (as[i].href) {
    window.location = as[i].href; // Browse to the URL.
  } else {
    // Not much we can do!
  }
}


So, this turns out to be a problem where every solution looks like a hammer, as we examine the problem assuming it's a nail.

The way to do this (and it's 100% cross browser) is simply to redirect the page to whatever addthis has set as the href to the link.

In otherwords...

self.location.href = document.getElementById("addThisFbLink").href;

That's all there is to it.

@kooilnc, I appreciate your solution, it wasn't what I needed, but in a way it led me to figuring this out, so thanks.


jQuery trigger():

Description: Execute all handlers and behaviors attached to the matched elements for the given event type.

$('a').trigger('click');
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜