【问题标题】:check radio button with jquery用 jquery 检查单选按钮
【发布时间】:2013-05-02 13:30:51
【问题描述】:

我有这段代码 sn-p 用 jquery 选中/取消选中单选按钮。

 $.each(options, function (index, item) {                   
                $optionli.find("li").eq(index)
                                    .find("input[type='radio']")
                                    .attr("checked", item.IsAnswer);

            });

item.IsAnswer 返回“true”或“false”,但未选中单选按钮,但在其 html 视图中,“checked”属性设置为“checked”

发生这种情况的原因可能是什么?

谢谢

【问题讨论】:

  • 我认为有一些用户界面问题。你有使用任何插件来改变radiobox的用户界面???
  • @mayur 不,我没有使用任何 ui 插件。
  • @Paras 你能用小提琴演示它并尝试复制它。
  • @PSCoder 我检查了这个小提琴jsfiddle.net/JpUF2/568 这里它似乎工作除了我注意到的区别是 attr() 和 prop() 之间。在 attr() 的情况下,即使未设置控件,也会设置“checked=checked”属性,而在 prop() 的情况下,会选中单选按钮但不会生成属性。

标签: jquery radio-button


【解决方案1】:

试试这个:- 使用 prop 而不是 attr

检查为属性不取真或假。 checked 的存在意味着它已被检查。

$.each(options, function (index, item) {                   
                $optionli.find("li").eq(index)
                                    .find("input[type='radio']")
                                    .prop("checked", item.IsAnswer);

            });

【讨论】:

    【解决方案2】:

    checked是一个属性,你应该使用prop方法,当一个布尔属性像disabled或checked被设置为一个元素时,该值被映射到元素的相关DOM属性(浏览器这样做) 和 attrremoveAttr 方法不会更改元素的属性,从 jQuery 1.6 开始用于修改属性,应使用 prop() 方法而不是 attr

    $('input[type=radio]').prop('checked', function(i, state){
            return !state;
        });
    

    【讨论】:

      猜你喜欢
      • 2016-08-17
      • 1970-01-01
      • 1970-01-01
      • 2019-05-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-24
      相关资源
      最近更新 更多