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");
});
});