【问题标题】:Input radio button function not working on jQuery 1.10.1输入单选按钮功能在 jQuery 1.10.1 上不起作用
【发布时间】:2014-05-13 08:00:41
【问题描述】:

为什么这段代码不能在 jQuery 1.10.1 上运行?
在这里摆弄 -> http://jsfiddle.net/XgDwU/9/

<input type="radio" id="don" name="billing[use_for_shipping]" value="">Ship to this address</input>
<input type="radio" id="don1" name="billing[use_for_shipping]" value="">Ship to different address</input>
<br/><br/>
<b> <input type="checkbox" id="chkSelect" /> Check/Uncheck me </b>
<br/><br/>
<p></p> 

这是我的功能

$(document).ready(function() {
  $('#chkSelect').click(function(){

    var isChecked = $('#chkSelect').is(':checked');
      if(isChecked){
          $("input#don").attr('checked',true);
          $('p').html('Checkbox is checked: <b>True</b>');
      }else{
          $("input#don1").attr('checked',true);
          $('p').html('Checkbox is checked: <b>False</b>');
      }
  });
});

【问题讨论】:

  • 什么不起作用??
  • 在第一个循环之后它停止。但如果你将 jQuery 版本更改为 1.6 或更高版本,它就可以正常工作了!

标签: javascript jquery input radio


【解决方案1】:

问题:

  1. 使用change 事件而不是click
  2. 使用prop 代替attr
  3. 我使用this.checked 代替$('#chkSelect').is(':checked')

试试

$(document).ready(function() {
    $('#chkSelect').change(function(){
      if(this.checked){
          $("input#don").prop('checked',true);
          $('p').html('Checkbox is checked: <b>True</b>');
      }else{
          $("input#don1").prop('checked',true);
          $('p').html('Checkbox is checked: <b>False</b>');
      }
    });
});

DEMO

你应该阅读.prop() vs .attr()提供了很好的解释

【讨论】:

【解决方案2】:

您正在尝试将检查属性添加到单选按钮。如果一组中的多个单选按钮具有checked 属性,则将检查后者。这就是正在发生的事情,正在检查不止一台收音机。

由于它是一个单选按钮,并且浏览器会处理切换,因此只需触发点击您想要的按钮即可:

$('#chkSelect').click(function () {
    if (this.checked) {
        $("input#don").click();
        $('p').html('Checkbox is checked: <b>True</b>');
    } else {
        $("input#don1").click();
        $('p').html('Checkbox is checked: <b>False</b>');
    }
});

JSFiddle

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-14
    • 1970-01-01
    • 2014-05-21
    • 1970-01-01
    • 2015-07-18
    • 1970-01-01
    • 1970-01-01
    • 2014-03-29
    相关资源
    最近更新 更多