需求:具有審核權限的一定會有更新、查看權限,具有更新權限的一定會有查看全選沒有選中查(cha)看權限的、一定沒有更新(xin)、審核權限
思路:根據value值來判斷,查看權限的value值會包含_find、更新權限的value值包含_mod、審核權限的value包含_review,在點擊checkbox的點擊事件上操作。
$(function() {
$("#modaltbody input[type='checkbox']").change(function(){
var str=$(this).val();
if(str.indexOf('review')>0) {
//審核
if($(this).is(":checked")) {
$(this).parent().parent().find("input").each(function(){
if($(this).val().indexOf('find')>0 || $(this).val().indexOf('mod'))
{
$(this).prop("checked",true);
}
})
}
else
{
$(this).prop("checked",false);
}
}else if(str.indexOf('mod')>0)
{
//修改
if($(this).is(":checked")) {
$(this).parent().parent().find("input").each(function(){
if($(this).val().indexOf('find')>0)
{
$(this).prop("checked",true);
}
})
}else
{
$(this).parent().parent().find("input").each(function(){
if($(this).val().indexOf('review')>0 || $(this).val().indexOf('mod')>0)
{
$(this).prop("checked",false);
}
})
}
}else {
//查看(kan)
if(!$(this).is(":checked"))
{
$(this).parent().parent().find("input").each(function(){
$(this).prop("checked",false);
})
}
}
})
});
jquery使(shi)用attr,removeAttr二次無法選中(zhong)的問題解(jie)決辦法
這里的選中checkbox、取消checkbox也可以(yi)用下(xia)面的寫法
$(this).attr("checked","checked");//選中
$(this).removeAttr("checked");//取消
這種寫法的缺點是在chrome瀏覽(lan)器中第一次點擊有效后面(mian)就不行(xing)了(le),IE8倒是沒有問題
百度了很久(jiu)找到原因是(shi)HTML的屬性分為attribute和property,暫且將(jiang)后者(zhe)稱(cheng)為特性。
checked屬性即(ji)分為attribute->checked,和(he)property->true,false。
對于一個checkbox,若未定義(yi)checked="checked",alert($.attr("checked")) 的結果是undefined。若已定義(yi)則(ze)結果是checked。attribute并不(bu)隨(sui)著(zhu)checkbox的狀態變化(hua)而改(gai)變。
使用(yong)prop($.attr("checked"))的話輸出則分別(bie)為false和true。property則隨其(qi)變化而變化。
所以在(zai)修改checked屬性時要使用prop()。prop()在(zai)jQuery1.6版本后新增。
另外(wai)關于在IE9之前(qian)版本中,如果property沒有在DOM元(yuan)素被移除之前(qian)刪除,使(shi)用.prop()方法設置DOM元(yuan)素property(簡單類型除外(wai):number、string、boolean)的值會(hui)導致內存(cun)泄(xie)露。為了安全的設置DOM對象(xiang)的值,避免內存(cun)泄(xie)露,可以使(shi)用.data()方法。 目(mu)前(qian)尚未遇到(dao),先記在這里。
$('#checkbox').attr('checked'); 返回的(de)是(shi)(shi)checked或者(zhe)是(shi)(shi)undefined,不是(shi)(shi)原來的(de)true和false了,有(you)關此問(wen)題的(de)解決方法如(ru)下。
在(zai)JQ1.6之(zhi)前的版本,我們會這樣寫我們的代碼:
這樣寫在JQ1.6之前完全沒問題,可是當我們升級JQ1.6到更高的版本時,問題就來了,此時我們會發現:
$('#cb').attr('checked'); 返回的(de)是(shi)checked或者是(shi)undefined,不(bu)(bu)是(shi)原來的(de)true和false了(le)。 并且checked屬(shu)性在頁(ye)面初始(shi)化(hua)的(de)時(shi)候已經初始(shi)化(hua)好(hao)了(le),不(bu)(bu)會隨著狀態(tai)的(de)改變(bian)而改變(bian)。所(suo)以如果checkbox一開始(shi)是(shi)選(xuan)中(zhong)(zhong)的(de),那么返回的(de)是(shi)checked,如果一開始(shi)沒被選(xuan)中(zhong)(zhong),則返回的(de)是(shi)undefined
分析了其中的原因,可以這樣理解:
它將“屬性”與“特性”做了區別,屬性指的是“name,id”等等,特性指的是“selectedIndex,
tagName, nodeName”等等。
JQ1.6之后,可(ke)以通過(guo)attr方法去獲(huo)(huo)得屬性,通過(guo)prop方法去獲(huo)(huo)得特性
1. $("#cb").attr("tagName"); //undefined
2. $("#cb").prop("tagName"); //INPUT
以上是蘇州網站制作小編在實際項目中(zhong)遇到的問(wen)題,記下了解決辦法(fa),額外搜集了相關(guan)信息,僅供參考,希(xi)望對遇到同樣問(wen)題的小伙伴(ban)有(you)幫(bang)助。