jQuery主要有三种选择器,分别为:
- 元素选择器
- 属性选择器
- CSS选择器
jQuery 元素选择器和属性选择器允许您通过标签名、属性名或内容对 HTML 元素进行选择。
选择器允许您对 HTML 元素组或单个元素进行操作。
1.jQuery 元素选择器
jQuery 使用 CSS 选择器来选取 HTML 元素。
例如:
jQuery 元素选择器
jQuery 使用 CSS 选择器来选取 HTML 元素。
例如:
$(“p”) 选取< p>元素。
$(“p.intro”) 选取所有 class=”intro” 的 < p>元素。
$(“p#demo”) 选取所有 id=”demo” 的< p>元素。
2.jQuery 属性选择器
jQuery 使用 XPath 表达式来选择带有给定属性的元素。
例如:
$(“[href]”) 选取所有带有 href 属性的元素。
$(“[href=’#’]”) 选取所有带有 href 值等于 “#” 的元素。
$(“[href!=’#’]”) 选取所有带有 href 值不等于 “#” 的元素。
$(“[href $=’.jpg’]”) 选取所有 href 值以 “.jpg” 结尾的元素。
3.jQuery CSS 选择器
jQuery CSS 选择器可用于改变 HTML 元素的 CSS 属性。
例如:
<html>
<head>
<script type="text/javascript" src="/jquery/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){
$("p").css("background-color","red"); //把所有 p 元素的背景颜色更改为红色
});
});
</script>
</head>
<body>
<h2>This is a heading</h2>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<button type="button">Click me</button>
</body>
</html>
运行结果如下: