关于Jquery mobile checkbox的全选及反选

1. jquery mobile 中的 checkbox

jquery mobile 对传统 html 进行了移动端优化,为了实现一些好看的效果而对html 标签进行了修改,如 checkbox:

普通 web 网页:     

<input type="checkbox" id="cb1" name="cb1" class="cb-mlb"/>  

Jquery mobile:

   <label for="cb1">计算机网络分层</label>
   <input type="checkbox" id="cb1" name="cb1" class="cb-mlb"/> 

 or

   <label for="cb1"> <input type="checkbox" id="cb1" name="cb1" class="cb-mlb"/>
计算机网络分层</label>
                  

 

另外,由于一些原因,当使用代码改变check 状态时,页面并不能自动显示,需要人工的进行刷新:

$("input[type='checkbox']").checkboxradio("refresh"); 

2. jquery mobile 中的 checkbox全选

网上给了很多攻略给的实现方法是:

选中:

$("input[type='checkbox']").attr("checked",true).checkboxradio("refresh"); 

不选:

$("input[type='checkbox']").attr("checked",false).checkboxradio("refresh");

试验后发现没有效果,原来问题出在 .attr()上面,在较新版本的 jquerymobile 中,新增了.prop()方法,

注:w3cshool 上没有找到此方法。

attr 与 prop 的区别

  • 对于html 中的原生属性,比如<a>中的 href,id,name 等属于原生属性,应使用 prop 进行操作。
  • 对于我们自定义的属性,比如 data-xxx,应使用 attr 进行操作。

checkbox 全选的正确姿势

选中:

$("input[type='checkbox']").prop("checked",true).checkboxradio("refresh"); 

不选:

$("input[type='checkbox']").prop("checked",false).checkboxradio("refresh");

代码示例:

HTML:

 <div data-role="main" class="ui-content" style="text-align: center">
            <label for="cb_all">全部选择</label>
            <input type="checkbox" id="cb_all" name="cb_all" class="cb-mlb" />
            <label for="cb1">计算机网络分层1</label>
            <input type="checkbox" id="cb1" name="cb1" class="cb-mlb" />
            <label for="cb2">计算机网络分层2</label>
            <input type="checkbox" id="cb2" name="cb2" class="cb-mlb" />
            <label for="cb3">计算机网络分层3</label>
            <input type="checkbox" id="cb3" name="cb3" class="cb-mlb" />
</div>

JS:

$(document).on("pagecreate", "#pageone", function () {
    $("#cb_all").change(function () {
        $(".cb-mlb").prop('checked', $(this).prop("checked"));
        $(".cb-mlb").checkboxradio("refresh");
        });
});

 

参考:jquerymobile checkbox 官网攻略

         stackoverflow

转载于:https://my.oschina.net/dyc1122/blog/859672

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值