jQuery --- 实现 checkbox 样式的单选框

这是之前写的一个模态框 要求单选 但是 要求radio的默认样式 太难看了 就想用checkbox + js 自己把它改成单选框 如下:

  html代码:

复制代码
<div class="list-item">
    <input type="checkbox" id="1" value="">
    <label for="1">Dance of the Reed Pipes</label>
</div>
<div class="list-item">
    <input type="checkbox" id="2" value="">
    <label for="2">Dance of the Reed Pies</label>
</div>
<div class="list-item">
    <input type="checkbox" id="3" value="">
    <label for="3">Dance of the Reed Pipes</label>
</div>
<div class="list-item">
    <input type="checkbox" id="4" value="">
    <label for="4">Dance of the Reed Pipes</label>
</div>
<div class="list-item">
    <input type="checkbox" id="5" value="">
    <label for="5">Dance of the Reed Pipes</label>
</div>
复制代码

  js代码:

复制代码
$(".list-item").click(function(){
     $(".list-item").find("input[type='checkbox']").prop("checked", false);//每次点击前,将所有checkbox置为 未选中
     var cobj = $(this).find("input[type='checkbox']");//当前点击的checkbox
     cobj.prop("checked", true);//将当前点击的checkbox置为选中状态
        //over
})
复制代码

  代码并不复杂 挺简单的 ,如果想获取点击的id,只要再加一句 

var itemId = cobj.attr("id");

  这样就可以了 

猜你喜欢

转载自www.cnblogs.com/amylis_chen/p/11520560.html