【问题标题】:jQuery group of radio buttons .change method [duplicate]jQuery单选按钮组.change方法[重复]
【发布时间】:2012-08-26 14:37:14
【问题描述】:

我正在使用带有单选按钮的表单,该单选按钮是一组收音机的一部分,一次只能选择一个(单选没问题)。其中一个收音机必须在每次未选中时(选择另一个收音机)选择不同的代码时触发一个代码,我使用.change 方法,当您单击它时它会触发代码,但在它失去选择时不会触发。我想要的是切换或能够知道它何时失去选择。

我可以将代码添加到其他无线电 .change 方法,但是有很多无线电集,这会很痛苦,我正在寻找一次性配置。

编辑

标记由 ASP MVC Razor 引擎制成,如下所示:

@Html.RadioButtonFor(x => x.SomeModel, new { @class = "special-radio" })
@* Other radios but without the 'specia-radio' class *@

js:

// logging
$(function(){
  $('.special-radio').change(function(){
    console.log('change');
  });
});

仅当您单击“特殊无线电”收音机时才会出现字符串更改。

【问题讨论】:

    标签: jquery radio-button


    【解决方案1】:

    未选中单选时不会触发任何事件,因为它是多余的。试试这个:

    http://jsfiddle.net/hmartiro/g4YqD/1/

    它在一组收音机上放置一个更改事件,如果所选收音机是特殊的,则只触发一个事件,否则触发另一个事件。

    【讨论】:

    • 它不完全适合我的问题,因为我有多组收音机,但这是一个很好的起点。
    • 如果要挑出一组,可以使用$('input[name=foo]')
    【解决方案2】:

    如果无法添加类。您可以为这些单选按钮使用带有标识符的容器。这样您就可以隔离更改事件。 DEMO FIDDLE

    var prev_data;
    $('#special_radios input').change(function(){
        var me = $(this);
        //running function for check
      $('#log').html('<p>firing event for check: '+ me.attr('id') +'</p>');
        if(prev_data)
          uncheck_method(prev_data);  
      prev_data = me;
    });
    
    //@param obj = jquery raidio object
    function uncheck_method(obj){
        $('#log').append('<p>firing event for uncheck: '+obj.attr('id')+'</p>');
        obj.prop('checked', false) 
        //console.log($('#special_radios input:checked'));
    }
    
    ​
    

    html

    <input type="radio" name="zz" id="5"/>
    <div id="special_radios">
       <input type="radio" name="rx" id="1"/>
       <input type="radio" name="ry"  id="2" />
       <input type="radio" name="rz" id="3"/>
       <input type="radio" name="ra"  id="4"/>
    </div>
    <div id="log"></div>
    ​
    

    【讨论】:

      【解决方案3】:

      简单的解决方案

      var newValue; // vale of checked radio button
      var oldValue; // value of unchecked radio button
      
      $('.special-radio').change(function(){
          oldValue = newValue;
          newValue = $(this).val();
      });
      

      如果 oldValue 和 newValue 相同,则表示没有取消选中。

      【讨论】:

        猜你喜欢
        • 2011-02-08
        • 1970-01-01
        • 2014-01-12
        • 1970-01-01
        • 2012-03-22
        • 2010-11-13
        • 2018-07-18
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多