jQuery 如何可對 checkbox 做出全選/全部取消
IPFS
jQuery 裡面經常遇到使用 checkbox 如何可以做成全選/全部取消
使用 attr 與 prop 的差異
- attr 永遠都是呈現初始值,與目前狀態無關,因此檢視 HTML 原始碼時是看不出變化的
- prop 會立即反映目前狀態。
如何正確取值?
- $('.checkbox').prop('checked'); // 正確取得為 true
- $('.checkbox').prop('checked', false); // 正確取得為 false
範例
- $('.checkbox-1').prop('checked'); // 回應為 true
- $('.checkbox-1').attr('checked'); // 回應為 checked
- $('.checkbox-2').prop('checked', false); // 回應為 false
- $('.checkbox-2').attr('checked'); // 這時候回應為 undefined
- $('.checkbox-3').prop('checked'); // 回應為 true
- $('.checkbox-3').attr('checked'); // 回應為 checked
所以針對 checkbox 正確就必須用 prop 而不是 attr 取值
Like my work? Don't forget to support and clap, let me know that you are with me on the road of creation. Keep this enthusiasm together!

- Author
- More