<input id="button" type="button" onclick="javascript:alert('hello')">
<a href='http://google.com' onclick="javascript:alert('hello')">Google</a>
想要触发点击事件。在网址地址栏中
javascript:document.getElementById("button").click(); //working find
javascript:document.getElementsByTagName("a")[0].click(); //not working, Why
这基本上是自动点击按钮接受/拒绝Facebook中的所有请求。
答案 0 :(得分:2)
JavaScript不支持点击主播(<a>
标记)。但是,有一种解决方法:使用一些自定义JavaScript代码,您可以模拟锚点击。
这是我创建的一个简短片段。即使您使用目标属性,它也会模拟您期望的操作。我构建了一个检查以查看该方法是否实际在锚点上运行,因此您甚至可以在按钮上使用此方法并期望正常行为。您只需将其添加到页面上的某个位置即可。我在Safari 5中测试了它。
Element.prototype.anchorClick = function() {
if (this.click) return this.click();
if (this.onclick) { var result = this.onclick(); if (!result) return result; }
switch (this.target) {
case '_blank': window.open(this.href); break;
case '_parent': parent.location = this.href; break;
case '_top': top.location = this.href; break;
case '_self': case '': window.location = this.href; break;
default: if (parent[this.target]) parent[this.target].location = this.href; else window.open(this.href); break;
}
return true;
}
您以这种方式使用代码段:
javascript:document.getElementById('anchor').anchorClick();
javascript:document.getElementsByTagName('a')[0].anchorClick();
这里是完整版,里面有一些评论:
Element.prototype.anchorClick = function() {
// If there's a click method, the element isn't an anchor
if (this.click) {
// Just run the click method instead
return this.click();
}
// Is there an onclick method?
if (this.onclick) {
// Run the method and get the result
var result = this.onclick();
// Isn't the result true?
if (!result) {
// Cancel the operation and return the result
return result;
}
}
// Check the target property
switch (this.target) {
// _blank means a new window
case '_blank':
// Open the window
window.open(this.href);
break;
// _parent means the parent frame
case '_parent':
parent.location = this.href;
break;
// _top means the top frame
case '_top':
top.location = this.href;
break;
// _self means the current frame
// When there's no value for the target property, this is the expected result
case '_self':
case '':
window.location = this.href;
break;
// The last option is a user specified frame
default:
// Does the frame actually exist?
if (parent[this.target]) {
// Yep, and we'll open the page in that frame
parent[this.target].location = this.href;
} else {
// Nope, the frame doesn't exist
// The expected behaviour (in Safari) is opening a new window
window.open(this.href);
}
break;
}
return true;
}
答案 1 :(得分:0)
onclick
在Chrome和Firefox3.6中为我工作:
javascript:document.getElementsByTagName("a")[0].onclick();