1. 程式人生 > 實用技巧 >js_attr_prop=全選/取消/反選

js_attr_prop=全選/取消/反選

<!DOCTYPE html>
<html lang="en">
<head>
<title>Title</title>
<meta charset="UTF-8">
<script src="jquery-3.5.1.js"></script>
</head>
<body>

<!--<input type="checkbox" id="ck">-->

<button onclick="selectall();">全選</button>
<button onclick="cancel();">取消</button>
<button onclick="reverse();">反選</button>

<table border="1">
<tr>
<td><input type="checkbox"></td>
<td>111</td>
</tr>

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

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

<script>

// $("#ck").attr("checked","true"); //
// $("#ck").removeAttr("checked") // 去除屬性“checked”


li=[1,2,3,4,5,6];
dic={"name":"li","age":"16","height":"181"};
// 迴圈
// $.each(li,function (x,y) {
// console.log(x); // 索引:0.1.2.3.4.5
// console.log(x,y); // x,y: 0-1,1-2,2-3..., 索引+列表數字
// });

// $.each(dic,function (x,y) { // $.each(dic,function (x,y)
// // console.log(x); // key
// console.log(x,y); // key和value
// })

// $(".div1 tr").each(function () { // $(".div1 tr").each(function ()
// console.log($(this).html());
// })

function selectall(){
$("table :checkbox").each(function () { // $("table :checkbox") input標籤可直接用此方法
$(this).prop("checked",true);
})
}

function cancel(){
$("table :checkbox").each(function () {
$(this).prop("checked",false);
// $(this).removeAttr("checked") // 直接刪除屬性,也可以達到效果
})
}

function reverse(){
$("table :checkbox").each(function () {
if ($(this).prop("checked")){
$(this).prop("checked",false);
}
else{
$(this).prop("checked",true);
}

})
}


// --- 不用str,直接用prop

</script>

</body>
</html>