【问题标题】:Simulate click on radio button模拟单击单选按钮
【发布时间】:2020-06-14 16:53:10
【问题描述】:

我需要模拟鼠标单击单选按钮,但该按钮仅被选中。如何使函数适用于案例?

$("input[value='0']").click();

$('input[name=level]').on('click', function(event) {
  switch ($(this).val()) {
    case '0':
      alert("zero");
      break;
    case '1':
      alert("one");
      break;
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<label>
1<input type="radio" class="option-input radio" checked value="1" name="level" />
0<input type="radio" class="option-input radio"  value="0" name="level" />
</label>

【问题讨论】:

    标签: javascript jquery triggers radio-button


    【解决方案1】:

    将触发器放在点击功能下方的元素上。您试图触发对尚未在 DOM 中定义的函数的点击。

    $('input[name=level]').on('click', function(event) {
      switch ($(this).val()) {
        case '0':
          alert("zero");
          break;
        case '1':
          alert("one");
          break;
      }
    });
    
    $("input[value=0]").trigger('click');
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <label>
    1<input type="radio" class="option-input radio" checked value="1" name="level" />
    0<input type="radio" class="option-input radio"  value="0" name="level" />
    </label>

    【讨论】:

    • 请注意$(selector).click(); 也是$(selector).trigger('click'); 的简写
    • @charlietfl,如果.click() 没有传递给它的参数,你是正确的。
    猜你喜欢
    • 2016-09-12
    • 2017-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-02
    • 1970-01-01
    • 1970-01-01
    • 2023-03-05
    相关资源
    最近更新 更多