使用按钮'通过JavaScript模拟按钮点击;s值,而不是其id

Simulate a button click via JavaScript using a button's value, not its id?

本文关键字:按钮 id 通过 JavaScript 模拟      更新时间:2023-09-26

我想使用按钮的值而不是id通过JavaScript模拟按钮点击。

这是使用按钮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.');">

我尝试过getElementByValue("按钮"(,但没有成功。

以下是我使用jQuery:的方法

http://jsfiddle.net/skilldrick/R27rQ/1/

$('input[type=checkbox]').click(function () {
    $('input[value=Button]').click();
}); 

但正如Senad所说,身份证更适合这类事情。

<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.');">

jsfiddle示例

    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
         }
      }
}

这就是解决方案。。。

HTML

<input type="checkbox" onClick="clickButton('Button');">Check the box to simulate a button click

但最好通过ID 来查找元素