【问题标题】:radio Buttons and .attr('checked','checked') does NOT work in IE7单选按钮和 .attr('checked','checked') 在 IE7 中不起作用
【发布时间】:2011-06-21 21:31:50
【问题描述】:

有没有办法在 IE7 中附加时检查单选按钮?

似乎在每个浏览器中都有效,但在 IE6,7 中似乎并不有效,尽管到处阅读我都在正确地执行它。我完全不知道为什么它不起作用。

var $itemVariantRowRadio = $("<input/>")
    .attr("type", "radio")
    .attr("name", "itemvariant")
    .addClass("itemvariant")
    .val('whatever');


    $itemVariantRowRadio.attr('checked', 'checked');
    $itemVariantRow.append($itemVariantRowRadio)

现在,如果我在 IE6/7 中执行 console.log($itemVariantRowRadio.attr('checked'),那么它会说它已设置为 TRUE,但实际上并没有检查或接收收音机。

噩梦!还有其他人遇到过这个问题并有任何解决方法吗?

【问题讨论】:

    标签: jquery internet-explorer-7 radio-button


    【解决方案1】:

    如果在 jQuery >= 1.6:

    使用prop,如下所示:.prop() vs .attr()

    $itemVariantRowRadio.prop('checked', true);
    

    如果在 jQuery

    $itemVariantRowRadio.attr('checked', true);
    

    还有:

    尝试像这样创建你的元素:

    var $itemVariantRowRadio = $("<input/>",{
         type: 'radio',
         name: 'itemvariant',
         class: 'itemvariant',
         checked: true,
         value: 'whatever'
    });
    $itemVariantRow.append($itemVariantRowRadio);
    

    见小提琴:http://jsfiddle.net/maniator/6CDf3/
    附加 2 个输入的示例:http://jsfiddle.net/maniator/6CDf3/2/

    【讨论】:

    • 哇 1.6 是什么时候发布的?现在是 1.6.1 ......当然必须有更好的解决方案。我的意思是这肯定直到 1.6 才被打破:D
    • @Neal - 我认为在所有 jQuery 版本中这应该是 .attr() - 这些是在插入 DOM 之前设置的初始属性。
    • @Dominic,我添加了一个小提琴演示
    • @Alnitak -- 我没有意识到这是 OP 正在做的事情,但是不,你应该使用 prop for checked 甚至在它进入 dom 之前
    • 嗯,我可能误解了stackoverflow.com/questions/5885471/… 的结论是什么
    【解决方案2】:

    试试:$itemVariantRowRadio.not(':checked').click().change();

    因此,您实际上单击了复选框,就像您作为用户使用鼠标所做的那样。 not(':checked') 会让你确定它之前没有被检查过。并在之后触发更改事件,因为 jQuery click 本身不会这样做。

    【讨论】:

      【解决方案3】:

      MSIE 不允许您在创建后更改 input 元素的 type

      http://bugs.jquery.com/ticket/1536http://api.jquery.com/jQuery/#jQuery2

      就这样创建它:

      $('<input type="radio">')
      

      【讨论】:

      • 这实际上似乎解决了它:)
      【解决方案4】:

      如果在将checked属性附加到dom后应用,则不需要触发click事件:http://jsfiddle.net/XjHUe/2/

      <div id='content'></div>
      var $itemVariantRowRadio = $("<input/>")
          .attr("type", "radio")
          .attr("name", "itemvariant")
          .addClass("itemvariant")
          .val('whatever');
      //$itemVariantRowRadio.attr("checked", true);
      $("#content").append($itemVariantRowRadio);
      $(".itemvariant").attr('checked',true);
      
      var val = $(".itemvariant").attr("checked");
      alert(val);
      

      【讨论】:

        猜你喜欢
        • 2017-11-17
        • 1970-01-01
        • 2015-02-25
        • 1970-01-01
        • 1970-01-01
        • 2019-01-01
        • 2013-02-22
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多