使用按钮的值而不是其 id 通过 JavaScript 模拟按钮单击?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7121369/
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
Simulate a button click via JavaScript using a button's value, not its id?
提问by mwdar
I want to Simulate a button click via JavaScript using a button's value, not its id.
我想使用按钮的值而不是其 id 通过 JavaScript 模拟按钮单击。
Here is the code using the button id
这是使用按钮 id 的代码
<input type="checkbox" onClick="document.getElementById('theSubmitButton').click();">Check the box to simulate a button click
<br>
<input type="button" name="theSubmitButton" id="theSubmitButton" value="Button" onClick="alert('The button was clicked.');">
I've tried getElementByValue('Button') but it didn't work.
我试过 getElementByValue('Button') 但没有用。
采纳答案by ant_Ti
<script type="text/javascript">
function getButtonByValue(value) {
var els = document.getElementsByTagName('input');
for (var i = 0, length = els.length; i < length; i++) {
var el = els[i];
if (el.type.toLowerCase() == 'button' && el.value.toLowerCase() == value.toLowerCase()) {
return el;
break;
}
}
}
</script>
<input type="checkbox" onClick="getButtonByValue('Button').click();">Check the box to simulate a button click
<br>
<input type="button" name="theSubmitButton" id="theSubmitButton" value="Button" onClick="alert('The button was clicked.');">
回答by Skilldrick
Here's how I'd do it using jQuery:
下面是我如何使用 jQuery 做到这一点:
http://jsfiddle.net/skilldrick/R27rQ/1/
http://jsfiddle.net/skilldrick/R27rQ/1/
$('input[type=checkbox]').click(function () {
$('input[value=Button]').click();
});
but as Senad said, IDs are much better-suited for this type of thing.
但正如 Senad 所说,ID 更适合这种类型的事情。
回答by Senad Me?kin
function clickButton(val)
{
var buttons = document.getElementsByTagName('input');
for(var i = 0; i < buttons.length; i++)
{
if(buttons[i].type == 'button' && buttons[i].value == val)
{
buttons[i].click();
break; //this will exit for loop, but if you want to click every button with the value button then comment this line
}
}
}
this is solution...
这是解决方案...
HTML
HTML
<input type="checkbox" onClick="clickButton('Button');">Check the box to simulate a button click
But its best to find element by its ID
但最好通过其 ID 查找元素