扫码一下
查看教程更方便
jquery 选择器允许您对 html 元素组或单个元素进行操作。
jquery 选择器允许您对 html 元素组或单个元素进行操作。
jquery 选择器基于元素的 id、类、类型、属性、属性值等"查找"(或选择)html 元素。 它基于已经存在的 css 选择器,除此之外,它还有一些自定义的选择器。
jquery 中所有选择器都以美元符号开头:$()
。
jquery 元素选择器基于元素名选取元素。
在页面中选取所有
元素:
$("p")
用户点击按钮后,所有
元素都隐藏:
$(document).ready(function(){
$("button").click(function(){
$("p").hide();
});
});
jquery #id
选择器通过 html 元素的 id 属性选取指定的元素。
页面中元素的 id 应该是唯一的,所以您要在页面中选取唯一的元素需要通过 #id 选择器。
通过id
选取元素语法如下:
$("#test")
当用户点击按钮后,有 id="test" 属性的元素将被隐藏:
$(document).ready(function(){
$("button").click(function(){
$("#test").hide();
});
});
jquery 类选择器可以通过指定的 class 查找元素。
语法如下:
$(".test")
用户点击按钮后所有带有 class="test" 属性的元素都隐藏:
$(document).ready(function(){
$("button").click(function(){
$(".test").hide();
});
});
语法 | 描述 | 实例 |
---|---|---|
$("*") | 选取所有元素 | |
$(this) | 选取当前 html 元素 | |
$("p.intro") | 选取 class 为 intro 的
|
|
$("p:first") | 选取第一个
|
|
$("ul li:first") | 选取第一个
元素的第一个 |
|
$("ul li:first-child") | 选取每个
元素的第一个
|
|
$("[href]") | 选取带有 href 属性的元素 | |
$("a[target='_blank']") | 选取所有 target 属性值等于 "_blank" 的
|
|
$("a[target!='_blank']") | 选取所有 target 属性值不等于 "_blank" 的 |
|
$(":button") | 选取所有 type="button" 的 元素 和
|
|
$("tr:even") | 选取偶数位置的
| |
$("tr:odd") | 选取奇数位置的
| |
如果您的网站包含许多页面,并且您希望您的 jquery 函数易于维护,那么请把您的 jquery 函数放到独立的 .js 文件中。
当我们在教程中演示 jquery 时,会将函数直接添加到
部分中。不过,把它们放到一个单独的文件中会更好,就像这样(通过 src 属性来引用文件):