什么是jQuery
jQuery is a fast, small, and feature-rich JavaScript library. It makes
things like HTML document traversal and manipulation, event handling,
animation, and Ajax much simpler with an easy-to-use API that works
across a multitude of browsers. With a combination of versatility and
extensibility, jQuery has changed the way that millions of people
write JavaScript. (摘自jQuery官网)
简而言之,jQuery是一个javascript的类库,能够有效简洁代码(简洁的DOM操作)、消除浏览器间差异、方便修改CSS和轻松实现动画等。
本篇文章为jQuery学习笔记(1):选择器。
使用jQuery
使用jQuery只需在页面<head>
中链接入jQuery文件即可:
<html>
<head>
<script src="code.jquery.com/jquery-3.4.1.min.js"></script>
...
</head>
<body>
...
</body>
</html>
选择器
jQuery中选择器可帮助我们快速定位(选择)一个或多个DOM节点。
按ID查找
//查找 <div id='a'>;
var div = $('#a');
按照ID查找$('#id')
;
按tag查找
var a = $('.red'); //所有节点包含'class="red"'都将返回
//如:
//<div class='red'>...</div>
//<p class='green red'>...</p>
选择多个节点:
var a = $('.red.green');//没有空格
//符合条件的节点:
//<div class="red green">...</div>
//<div class="blue green red">...</div>
”并“∪,同时选择,无空格$('.class1.class2')//类名同时等于class1和class2的
按tag查找$('#id')
按属性查找
var icons = $('[name ^= icon]');//找出所有以icon开头的DOM
//例如:name = 'icon-1',name = 'icon-2';
var icons = $('[name $= with]');//找出所有以with结尾的DOM
//例如:name = 'starwith',name = 'endwith';
//也可直接查找完整的属性。
^= //以什么开头
&= //以什么结尾
组合查找
var emailIput = $('input[name=email]');
//不会查找出<div name='email'>
var tr = $('tr.red');
//找出<tr class='red...'>...</tr>
多项选择器
即组合起来选择。
$('p,div');//将<p>和<div>都选出来
$('p.red,p.green');//将两者都选择出来,用逗号隔开
$('.class1 .class2') //中间加空格表示:类class1下面的class2
$('.class1,.class2') //中间加逗号表示:类class1和类class2两个都
层级选择器
当DOM元素之间具有层级关系时,可以用$('ancestor descendant')
来选择,层级之间用空格分开。
//例如:
$('ul.lang li'); //选择出在<ul class='lang'>下面的所有<li>
子选择器
子选择器$('parent>child')
类似层级选择器,但是限定了层级关系必须是父子关系。不构成父子关系无法选出。
$('ul.lang>li.lang-javascript');
过滤器
$('ul.lang li'); // 选出JavaScript、Python和Lua 3个节点
$('ul.lang li:first-child'); // 仅选出JavaScript
$('ul.lang li:last-child'); // 仅选出Lua
$('ul.lang li:nth-child(2)'); // 选出第N个元素,N从1开始
$('ul.lang li:nth-child(even)'); // 选出序号为偶数的元素
$('ul.lang li:nth-child(odd)'); // 选出序号为奇数的元素
…
除以上选择器类型以外,jQuery还有很多有用的选择器,如表单相关的选择器等。
(我学的有点慢= =)