一、基本选择器
1. #id
匹配元素中的id属性的值
<body>
<div id="div1">div1</div>
<p id="p1">p1</p>
<div id="div2">div2</div>
<p id="p2">p2</p>
<script type="text/javascript">
console.log($('#div1'));
console.log($('#p2'));
</script>
</body>
2. .class
根据给定的css类名匹配元素
<body>
<div class="myClass">div1</div>
<div class="myClass">div2</div>
<p class="myClass">p1</p>
<div class="mydiv">div3</div>
<p class="myp2">p2</p>
<script type="text/javascript">
console.log($('.myClass'));
console.log($('.myp2'));
</script>
</body>
3. element
根据给定的元素标签名匹配所有元素
<body>
<div id="div1">div1</div>
<div id="div2">div2</div>
<p id="p1">p1</p>
<p id="p2">p2</p>
<p id="p3">p3</p>
<script type="text/javascript">
var div = $('div');
console.log(div);
var p = $('p');
console.log(p);
</script>
</body>
二、层级选择器
1. ancestor descendant
匹配给定元素的所有后代元素
<body>
<form>
<label for="uaername">用户名</label>
<input type="text" id="uaername" name="username">
<label for="pwd">密码</label>
<input type="password" id="pwd" name="pwd">
<div id="d1">
<label for="email">邮箱</label>
<input type="email" id="email" name="email">
</div>
</form>
<input type="text" name="none" id="one">
<script type="text/javascript">
var temp = $('form input');
console.log(temp);
console.log($('#d1 *')); // id为d1的所有子元素
console.log($('#d1 input'));
</script>
</body>
2. parent > child
在给定的父元素下匹配所有的直接子元素
<body>
<form>
<label for="uaername">用户名</label>
<input type="text" id="uaername" name="username">
<label for="pwd">密码</label>
<input type="password" id="pwd" name="pwd">
<div id="d1">
<label for="email">邮箱</label>
<input type="email" id="email" name="email">
<p>
<input type="number" id="number">
</p>
</div>
</form>
<input type="text" name="none" id="one">
<script type="text/javascript">
console.log($('form > input'));
console.log($('#d1 > input'));
</script>
</body>
3. prev + next
匹配所有紧接在 prev 元素后的 next 元素
<body>
<div id="div1">div1</div>
<div id="div2">
<div id="div2_1">div2_1</div>
<p>
<div id="div_p">div_p</div>
</p>
</div>
<p id="pw">pw</p>
<div id="div3">div3</div>
<script type="text/javascript">
console.log($('#div1 + *'));
console.log($('#div1 + div'));
console.log($('#div1 + p')); // 找不到
console.log($('p + div'));
</script>
</body>
4. prev ~ siblings
匹配 prev 元素之后的所有 siblings 元素
<body>
<div id="div1">div1</div>
<div id="div2">
<div id="div2_1">div2_1</div>
<p>
<div id="div_p">div_p</div>
</p>
</div>
<p id="pw">pw</p>
<div id="div3">div3</div>
<script type="text/javascript">
console.log($('#div1 ~ div'));
console.log($('#div1 ~ p'));
console.log($('#div2 ~ *'));
</script>
</body>
三、总结
基本掌握了jQuery基本选择器和层级选择器的用法。