问题
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 the 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?
回答1:
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();
回答2:
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.
回答3:
jQuery trigger():
Description: Execute all handlers and behaviors attached to the matched elements for the given event type.
$('a').trigger('click');
回答4:
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.
回答5:
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!
}
}
来源:https://stackoverflow.com/questions/6296588/is-it-possible-to-manually-call-a-click-on-a-dom-object