jquery全选,取消全选
近期項目又用到了這個全選和取消全選的操作.
曾經總是自己寫純JS.如今既然知道怎么寫了.那怎樣用JQ寫得更簡潔呢.這樣也能學到新的東西.假設乎百度一下果然發現了好東東.感謝OSC的iuhoay.
代碼例如以下:
- <script type="text/javascript" src="/web/bzz_index/password/js/jquery-1.7.1.min.js"></script>
- <script language="JavaScript">
- $(function() {
- $("#ckAll").click(function() {
- $("input[name='sub']").prop("checked", this.checked);
- });
- $("input[name='sub']").click(function() {
- var $subs = $("input[name='sub']");
- $("#ckAll").prop("checked" , $subs.length == $subs.filter(":checked").length ? true :false);
- });
- });
- </script>
- <input type="checkbox" id="ckAll" />check all<br />
- <input type="checkbox" name="sub" />1<br />
- <input type="checkbox" name="sub"/>2<br />
- <input type="checkbox" name="sub"/>3<br />
- <input type="checkbox" name="sub"/>4<br />
必須說的是JQ1.6+以上才支持prop哦.關于prop能夠看看以下這個.
今天在用JQuery的時候發現一個問題用.attr("checked")獲取checkbox的checked屬性時選中的時候能夠取到值,值為"checked"但沒選中獲取值就是undefined.
解決這個文章我參考了這個帖子:
http://bugs.jquery.com/ticket/9812
所以。從1.6開始,jq提供新的方法“prop”來獲取這些屬性。
但有下面三點。須要注意(摘自黑暗運行緒):
- $(window).attr(), $(document).attr()建議改為$(windows).prop(), $(document).prop()。由于window及document理論上無從加上HTML Attribute。盡管jQuery 1.6.1在內部會偷偷改用.prop()。畢竟語意不合邏輯。應該避免。
- 在HTML語法<input type=”checkbox” checked=”checked” />中。checked Attribute僅僅會在一開始將checked Property設成true,興許的狀態變更及儲存都是透過checked Property。
換句話說。checked Attribute僅僅影響初值,之后應以checked Property為準。
基于這個理由,$(“:checkbox”).prop(“checked”, true)會比$(“:checkbox”).attr(“checked”,
true)來得合理。盡管jQuery 1.6.1已讓$(“:checkbox”).attr(“checked”, true)也具有變更checked
Property的能力,但prop()確實比attr()寫法更吻合背后的實際運作。- 適用此點的Boolean屬性包括了: autofocus, autoplay, async, checked, controls, defer, disabled, hidden, loop, multiple, open, readonly, required, scoped, selected
jQuery Team提供一張DOM元素屬性適用attr()/prop()的對比表:
| Attribute/Property | .attr() |
.prop() |
|---|---|---|
| accesskey | ? | |
| align | ? | |
| async | ? | ? |
| autofocus | ? | ? |
| checked | ? | ? |
| class | ? | |
| contenteditable | ? | |
| defaultValue | ? | |
| draggable | ? | |
| href | ? | |
| id | ? | |
| label | ? | |
| location * | ? | ? |
| multiple | ? | ? |
| nodeName | ? | |
| nodeType | ? | |
| readOnly | ? | ? |
| rel | ? | |
| selected | ? | ? |
| selectedIndex | ? | |
| src | ? | |
| style | ? | |
| tabindex | ? | |
| tagName | ? | |
| title | ? | |
| type | ? | |
| width ** | ? |
總結
以上是生活随笔為你收集整理的jquery全选,取消全选的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: byte[],bitmap,drawab
- 下一篇: windows中检查端口占用