JavaScript 单击图像按钮
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11147370/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JavaScript Click Image Button
提问by Nubcake
This is my second question about clicking buttons in JavaScript but this one I'm really stuk on: I'm trying to click an image button with javascript however there's not much to go on as the source only gives this information about the image button
这是我关于在 JavaScript 中单击按钮的第二个问题,但我真的很关心这个问题:我正在尝试使用 javascript 单击图像按钮,但是没有太多可做的,因为源仅提供有关图像按钮的信息
<div id="claimBtnDv" style="bottom:-30px; position:absolute; right:0; margin-top:0;">
<input type="image" class="btnClaim" src="websitebuttonimage" onclick="alert('buttonclicked');">
</div>
I tried to do document.getElementById('claimBtnDv').click()
but no success , are there other methods to use?
我尝试过document.getElementById('claimBtnDv').click()
但没有成功,还有其他方法可以使用吗?
回答by Arlen Anderson
If you can't change the HTML and you need to click the image using javascript, you can go into the child nodes to find the image. This is pretty easy since a class name is provided.
如果无法更改 HTML 并且需要使用 javascript 单击图像,则可以进入子节点查找图像。这很容易,因为提供了类名。
var nodes = document.getElementById('claimBtnDv').childNodes;
for ( i = 0; i < nodes.length; i++ ) {
if ( nodes[i].className === "btnClaim" ) {
console.log("clicking!");
nodes[i].click();
break;
}
}
回答by Zoltan Toth
Your code almost works - just change your class="btnClaim"
to id="btnClaim"
- and the getElementById
will work - http://jsfiddle.net/wMRbn/1/
您的代码几乎可以工作 - 只需将您更改class="btnClaim"
为id="btnClaim"
- 即可getElementById
- http://jsfiddle.net/wMRbn/1/
document.getElementById('btnClaim').onclick = function () {
alert ( "click" );
}?
UPDATETo get an element without an id
you can do this - get the parent element by id
and attach an event listener to its' input
child - http://jsfiddle.net/wMRbn/3/
更新要获取没有的元素,id
您可以执行此操作 - 通过获取父元素id
并将事件侦听器附加到其input
子元素- http://jsfiddle.net/wMRbn/3/
var img = document.getElementById("claimBtnDv").getElementsByTagName("input")[0];
img.onclick = function () {
alert ( "click" );
}?
回答by Fallenreaper
it looks like it works in that case. Are you trying to assign it different click events or something?
看起来它在这种情况下有效。您是否尝试为其分配不同的点击事件或其他内容?
jquery would allow you to do something like:
jquery 将允许您执行以下操作:
$("input.btnClaim").click(function(){
//in here can go a lot more functions, etc.
});
javascript would do (after you give it an id of 'btnClaim'):
javascript 会做(在你给它一个 'btnClaim' id 之后):
var X = document.getElementById("btnClaim");
x.onclick = "JAVASCRIPT GOES HERE";
//from what the wc3 doc looks like, you need to have it in quotes,
// but i may be mistaken.
Maybe that helps ?
也许这有帮助?