jQuery语法
jQuery 语法是通过选取 HTML 元素,并对选取的元素执行某些操作。
基础语法: (selector).action()定义 jQuery
选择符(selector)”查询”和”查找” HTML 元素
jQuery 的 action() 执行对元素的操作
小结:
$(this).hide() - 隐藏当前元素
$("p").hide() - 隐藏所有 <p> 元素
$("p.test").hide() - 隐藏所有 class="test" 的 <p> 元素
元素选择器
jQuery 元素选择器基于元素名选取元素。
--用户点击按钮button后,所有 <p> 元素都隐藏:
$(function(){
$("button").click(function(){
$("p").hide();
});
});
id 选择器
jQuery #id 选择器通过 HTML 元素的 id 属性选取指定的元素。
页面中元素的 id 应该是唯一的,所以您要在页面中选取唯一的元素需要通过 #id 选择器。
--当用户点击按钮后,有 id="test" 属性的元素将被隐藏:
$(document).ready(function(){
$("button").click(function(){
$("#test").hide();
});
});
.class 选择器
jQuery 类选择器可以通过指定的 class 查找元素。
--用户点击按钮后所有带有 class="test" 属性的元素都隐藏:
$(document).ready(function(){
$("button").click(function(){
$(".test").hiden();
});
});
更多的selector选择符
扩展
扩展 | |
---|---|
$(“*”) | 选取所有元素 |
$(this) | 选取当前 HTML 元素 |
$(“p.test”) | 选取 class 为 test 的 p 元素 |
$(“p:first”) | 选取第一个 p 元素 |
$(“ul li:first”) | 选取第一个ul的第一个li元素 |
$(“ul li:first-child”) | 选取每个ul的第一个li元素 |
$(“[href]”) | 选取带有 href 属性的元素 |
$(“a[target=’_blank’]”) | 选取所有 target 属性值等于 “_blank” 的 a元素 |
$(“a[target!=’_blank’]”) | 选取所有 target 属性值不等于 “_blank” 的 a 元素 |
$(“tr:even”) | 选取偶数位置的tr 元素 |
$(“tr:odd”) | 选取奇数位置的 tr 元素 |