层级选择器(> 选择form的直接子元素)可能有多个
<script type="text/javascript">
$(function(){
alert($("form > input").length);
})
</script>
<form>
<label>Name:</label>
<input objName="ext" name="newsletter" />
<input objName="ext2" name="newsletter" />
<span style="white-space:pre"> </span><span style="white-space:pre">
<span style="white-space:pre"> </span><input objName="ext" name="newsletter" />
<span style="white-space:pre"> </span></span>
<span style="white-space:pre"> </span><span style="color:#ff0000;">
<span style="white-space:pre"> </span><input objName="ext" name="newsletter" />
<span style="white-space:pre"> </span></span>
<span style="white-space:pre"> </span><span style="white-space:pre">
<span style="white-space:pre"> </span>
<span style="white-space:pre"> </span></span>
<span style="white-space:pre"> </span><fieldset>
<label>Newsletter:</label>
<input objName="inner" name="newsletter" />
</fieldset>
</form>
层级选择器( + 匹配所有紧接在 prev 元素后的 next 元素)最多一个
<script type="text/javascript">
$(function(){
var arr = $("label + input");
for(var i = 0; i<arr.length; i++) {
alert($(arr[i]).attr("objName"));
}
/*
$("label + input").each(function() {
alert($(this).attr("objName"));
})
*/
})
</script>
<form>
<label>Name:</label>
<p>------</p>
<input objName="ext" name="newsletter1111" />
<fieldset>
<label>Newsletter:</label>
<span style="color:#ff0000;"><input objName="inner" name="newsletter1111" /></span>
</fieldset>
</form>
层级选择器( ~匹配 prev 元素之后的所有 siblings 元素)可能有多个
<script type="text/javascript">
$(function(){
var arr = $("label#ext ~ input");
for(var i = 0; i<arr.length; i++) {
alert($(arr[i]).attr("objName"));
}
})
</script>
<label id="ext">Name:</label>
<span style="color:#ff0000;"><input objName="ext" name="newsletter1111" />
<input objName="ext1" name="newsletter1111" /></span>
<fieldset>
<span style="white-space:pre"> </span><label>Newsletter:</label>
<span style="white-space:pre"> </span><input objName="inner" name="newsletter1111" />
</fieldset>
- 子元素(:nth-child 匹配其父元素下的第N个子或奇偶元素)注:nth-child下标从1开始,其他从0开始,2n中的n从0开始,可使用odd,even
$(function(){
var a = $("ul li:nth-child(1)");
var b = $("ul li:nth-child(2n)");
var c = $("ul li:nth-child(2n+1)");
var d = $("ul li:nth-child(odd)");
})
<ul>
<li>John</li>
<li>Karl</li>
<li>Brandon</li>
<li>Glen</li>
<li>Tane</li>
<li>Ralph</li>
</ul>
$(function(){
var a = $("ul li:nth-child(1)");
var b = $("ul li:nth-child(2n)");
var c = $("ul li:nth-child(2n+1)");
var d = $("ul li:nth-child(odd)");
})
<ul>
<li>John</li>
<li>Karl</li>
<li>Brandon</li>
<li>Glen</li>
<li>Tane</li>
<li>Ralph</li>
</ul>