【问题标题】:Detecting programmatic change of radio button in Jquery检测 Jquery 中单选按钮的编程更改
【发布时间】:2022-01-22 23:49:37
【问题描述】:

您可以在我的示例中看到,手动单击收音机会触发警报,但单击选中/取消选中链接(以编程方式执行此操作)不会。

https://codepen.io/PeteWilliams/pen/xxXLpYE


    <!DOCTYPE html>
    <html>
      <head>
    
    <script src="https://code.jquery.com/jquery-2.2.4.js"></script>
      
    <script>
    
        $(document).ready(function() {
    
    
            $('input[type=radio]').change(function() {
                alert(' changed');
            });
    
    
    });
    
    </script>
    </head>
      <body>
    
    
            <p>
                <label for="radio1" > RADIO BUTTON
                <input id="radio1" type="radio" />
            </label>
            </p>
    
            <p>
                <a href="#" onclick="$('#radio1').prop('checked', true ); return false;">check</a>
            </p>
    
            <p>
                <a href="#" onclick="$('#radio1').prop('checked', false ); return false;">uncheck</a>
            </p>
    
      </body>
    </html>

看起来 .change() 仅在用户交互时触发,而不仅仅是 任何 更改。

还有其他方法可以实现这个目标吗?在这种情况下,我无法更改选择/取消选择收音机的代码,只能更改选择它的代码。

【问题讨论】:

    标签: javascript html jquery radio-button


    【解决方案1】:

    确实,如果您以编程方式更新输入,则不会引发 change 事件。使用 jQuery 执行此操作的一种方法是使用 .trigger() 函数手动引发事件:

    function check() {
      const radio = $("#radio1");
      radio.prop('checked', true);
      radio.trigger('change')
    }
    
    function uncheck() {
      const radio = $("#radio1");
      radio.prop('checked', false);
      radio.trigger('change')
    }
    
    
    $(document).ready(function() {
        $('input[type=radio]').change(function() {
            alert('changed');
        });
    });
    <!DOCTYPE html>
    <html>
      <head>
        <script src="https://code.jquery.com/jquery-2.2.4.js"></script>
      </head>
      <body>
        <label for="radio1" > RADIO BUTTON</label>
        <input id="radio1" type="radio" />
    
        <p>
          <a href="#" onclick="check()">check</a>
        </p>
    
        <p>
          <a href="#" onclick="uncheck()">uncheck</a>
        </p>
    
      </body>
    </html>

    来源:https://api.jquery.com/trigger/

    【讨论】:

    • 谢谢,但不幸的是,在这种情况下,我无法更改检查/取消检查行为 - 我需要能够独立检测它。
    • @PeteWilliams 你不能同时覆盖元素的onclick 函数吗?
    猜你喜欢
    • 1970-01-01
    • 2023-04-03
    • 1970-01-01
    • 2016-01-22
    • 1970-01-01
    • 2021-11-14
    • 2021-10-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多