【问题标题】:Simulate a button click via JavaScript using a button's value, not its id?使用按钮的值而不是其 id 通过 JavaScript 模拟按钮单击?
【发布时间】:2011-10-30 14:03:10
【问题描述】:

我想通过 JavaScript 使用按钮的值而不是其 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.');">

我试过 getElementByValue('Button') 但没用。

【问题讨论】:

  • 它对我来说很好用:jsfiddle.net/pimvdb/R27rQ.
  • @pimvdb 该解决方案仍然使用 id。
  • @jncraton:我误解了这个问题。没明白“不”是什么意思。
  • 不知道为什么要这样做,但它在 OS X Lion 和 Chrome 中对我不起作用。如中,警报出现,但按钮单击没有动画。

标签: javascript button click


【解决方案1】:

这是我使用 jQuery 的方法:

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

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

但正如 Senad 所说,ID 更适合这类事情。

【讨论】:

    【解决方案2】:
    <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 example

    【讨论】:

      【解决方案3】:
          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 找到元素

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-11-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多