屬性選擇器中的類別:
1、[attribute] 匹配包含給定屬性的元素 例:查找所有含id屬性的div元素;$("div[id]");
2、[attribute=value] 匹配給定的屬性是某個特定值的元素 例:查找所有name屬性是newsletter的input元素:$("input[name="newsletter"]").attr("checked",true);
3、[attribute!=value] 匹配給定的屬性是不包含某個特定值的元素 例:查找所有name屬性不是newsletter的input元素:$("input[name!='newsletter']").attr("checked",true);
4、[attribute^=value] 匹配給定的屬性是以某些值開始的元素 例:$("input[name^='news']");
5、[attribute$=value] 匹配給定的屬性是以某些值結尾的元素 例: 查找 name 以“letter”結尾的input元素:$("input[name$='letter']")
6、[attribute*=value] 匹配給定的屬性是以包含某些值的元素 例:查找所有name包含‘man’的input元素:$("input[name*='man']")
7、[attributeFilter1][attributeFilter2][attributeFilterN] 複合屬性選擇器,需要同時滿足多個條件時使用。 例:查找所有含有id屬性,並且它的name屬性是以man結尾:$("input[id][name$='man']")
網頁實例(參考):
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head>
- <title></title>
- <style type="text/css">
- div
- {
- width:200px; height:100px; border:2px solid red; background-color:#eee;
- }
- img
- {
- width:200px; height:200px;
- }
- </style>
- <script src="jquery-1.9.1.js" type="text/javascript"></script>
- <script type="text/javascript">
- $(function () {
- $('#btn1').click(function () {
- var sum = $('[title]');
- for (var i = 0; i < sum.length; i++) {
- alert(sum[i].nodeName);
- }
- $('div[title]').css('background-color', 'blue'); //獲取所有div中具有titile屬性的元素
- $('div[title=t2]').css('background-color', 'blue'); //獲取所有div中title等於t2的元素
- $('div[title!=t2]').css('background-color', 'blue'); //獲取所有div中title不等於t2的元素
- $('div[title^=t]').css('background-color', 'blue');//獲取所有div中title屬性開頭是t的元素
- $('div[title$=2]').css('background-color','blue')//獲取所有div中title屬性包含2的元素
- $('div[title*=s]').css('background-color', 'blue');//獲取所有div中title屬性結尾是s的元素
- $('div[title^=t][title$=4]').css('background-color','blue');//獲取所有title屬性開頭是t,結尾是4的元素
- })
- })
- </script>
- </head>
- <body>
- <div id="t1" title="t1">第一層</div>
- <div title="t2">第二層</div>
- <div id="div3" title="r3s">第三層</div>
- <div id="div4" title="r4">第四層</div>
- <img src="beijing.jpg" />
- <input type="button" id="btn1" value="提交" />
- </body>
- </html>