【问题标题】:How to make a Radio button with the same properties of a Checkbox using jQuery如何使用 jQuery 制作具有与复选框相同属性的单选按钮
【发布时间】:2011-09-18 20:21:47
【问题描述】:

我的 HTML 代码是

  <table>
    <tr><td><input type="checkbox"></td><td><input type="checkbox"></td></tr>
    <tr><td><input type="checkbox"></td><td><input type="checkbox"></td></tr>
    <tr><td><input type="checkbox"></td><td><input type="checkbox"></td></tr>
    <tr><td><input type="checkbox"></td><td><input type="checkbox"></td></tr>
    <tr><td><input type="checkbox"></td><td><input type="checkbox"></td></tr>
    <tr><td><input type="checkbox"></td><td><input type="checkbox"></td></tr>
    <tr><td><input type="checkbox"></td><td><input type="checkbox"></td></tr>
    <tr><td><input type="checkbox"></td><td><input type="checkbox"></td></tr>
   </table>

我的 JQuery 代码是(不是我写的,一些 Stackoverflow 的使用帮助了我,我感谢他)

     $('TABLE TBODY TR').each(function()     
      {       
       var lastd =    $(this).children('tr td:last').find('input:checkbox');    
       var parentlast =   lastd.parent();       
       lastd.remove();           
       parentlast.append("<input type='radio'>"); // want to add the same properties of the removed checkbox     
      });  

请有人帮助我。

【问题讨论】:

  • 并不是说它真的很重要,但为什么要这样做呢?基于人们的期望,你会把他们搞糊涂。 (例如,如果我看到一个复选框,我希望能够选择多个项目。如果我看到一个单选按钮,我希望只能选择一个。)您更改约定的任何原因?我只是好奇。
  • 有什么理由不能只渲染radio 类型的输入吗?
  • 我的服务器在表格中生成所有复选框,这是我们的要求,但在某些情况下,我们使用最后一个复选框作为独占。这就是我想要这样做的原因:-)
  • @JasCav:虽然我通常建议不要更改常规约定,但 OP 所要求的内容可能不会让普通用户感到困惑,具体取决于他的应用程序。

标签: jquery jquery-ui radio-button dom-manipulation html


【解决方案1】:

嗯,我不明白你为什么要这样做,但你可以把它变成一个单选按钮。

$('tr:last td:last input:checkbox').prop('type', 'radio');

(本示例使用 jQuery 1.6)

JsFiddle Demo

更新:正如@kei 正确指出的那样,这个在IE

var $csekk=$('tr:last td:last input:checkbox'),
    $klon=$csekk.clone().attr('type', 'radio');

$csekk.after($klon).remove();

JsFiddle Demo

这个基本上克隆了复选框(以保留您可能与之关联的每个属性),将克隆更改为单选,插入并删除旧的。

【讨论】:

  • IE8(我也用浏览器模式测试到IE7,不允许更改)
  • @kei 是的,你是对的,谢谢。而是写了一个简单的克隆。
【解决方案2】:

这是一个使用 jQuery、CSS 和图像精灵自定义单选按钮和复选框的插件和教程。

Accessible, Custom Designed Checkbox and Radio Button Inputs Styled with CSS (and a dash of jQuery)

由于您将使用自定义创建的精灵,您可以简单地使它们看起来像您想要的任何东西。

【讨论】:

    【解决方案3】:

    希望这能解决您的问题。

     $('TABLE TBODY TR').each(function()
        {  
        var lastd =    $(this).children('tr td:last').find('input:checkbox');  
         var parentlast =   lastd.parent();
          lastd.remove();     
          parentlast.append("<input type='radio'>");
    
        });
    

    所以基本上它会找到最后一个复选框,将其从 dom 中删除,然后创建一个新的

    【讨论】:

    • 您正在向右附加一个单选按钮,但是我如何将具有相同属性的相同单选按钮添加到该单选按钮,例如 id、该复选框的名称
    • parentlast.append("");
    猜你喜欢
    • 2010-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-18
    相关资源
    最近更新 更多