jQuery只是一个jquery-xxx.js文件,可以从jQuery官网下载最新版本。
使用,引入jQuery文件即可:

选择器
基本选择器
-
按id查找,id前需要添加:#
image.png
-
按tag查找
按tag查找,只需要写上tag名称就可以了
image.png
-
按class查找,class前需要添加:.
image.png
如果有多个class,可以查找同时包含多个class的节点
image.png
-
按属性查找,属性用中括号括起来
当属性的值包含空格等特殊字符时,需要用双引号括起来
image.png
还可以使用前缀查找或者后缀查找
image.png
image.png
-
组合查找
image.png
image.png
多项选择器
多项选择器就是把多个选择器用逗号组合起来一起用

层级选择器
如果两个DOM元素具有丛集关系,可以用$('ancestor descendant')来选择,层级之间用空格隔开。
例如:

要选出JavaScript:

层级选择器相比单个选择器好处在于,缩小了选择范围。
过滤器(Filter)
过滤器一般不单独使用,它通常附加在选择器上,帮助更精确地定位元素。

表单相关
针对表单元素,jQquery还有一组特殊的选择器
- :input,可以选择<input>,<textarea>,<select>,<button>
- :file,可以选择<input type='file'>,和input[type=file]一样
- :checkbox,可以选择复选框,和input[type=checkbox]一样
- :radio,可以选择单选框,和input[type=radio]一样
- :focus,可以选择当前输入焦点的元素,例如把光标放到一个<input>上,用$('input:focus')就可以选出
- :checked,选择当前勾上的单选框或复选框,用这个可以立即获取用户选择的项目,如$('input[type=radio]:checked')
- :enabled,可以选择可以争取正常输入的<input>、<select>等,也就是没有灰掉的输入
- :disabled,和:enabled相反,选择不能输入的
- :visible,选择可见的
-
:hidden,选择隐藏的
image.png
查找
通常情况下选择器可以直接定位到我们想要的元素,但是,当我们拿到一个jQuery对象后,还可以以这个对象为基准,进行查找和过滤。最常见的查找是在某个节点的所有子节点中查找,使用find()方法,它本身又接收一个任意的选择器。
如:

用find()查找:

如果要从当前节点开始向上查找,使用parent()方法:

对于同一层级节点,可以通过next()和prev()方法:

过滤
和函数式编程中的map、fileter类似,jQuery对象也有类似的方法
filter()可以过滤掉不符合选择器条件的节点:

或者传入一个函数,要特别注意函数内部的this被绑定为DOM对象,不是jQuery对象:

map()方法把一个jQuery对象包含的若干DOM节点转化为其他对象:

如果,一个jQuery对象不只包含了一个DOM节点,first()、last()和slice()方法可以返回一个新的jQuery对象,把不需要的DOM节点去掉:

操作DOM
修改text和html
jQuery对象的text()和html()方法分别获取节点的文本和原始html文本
如:

分别获取文本和html:

设置文本或html,无参数调用是获取,传入参数就是设置:

修改css
如:

要高亮显示动态语言,调用jQuery对象的 css('name', 'value') 方法:

jQuery对象的 css() 方法可以这么用:

css()方法作用于DOM节点的style属性,具有最高优先级。如果要修改class属性:

attr()和removeAttr()方法用于操作DOM节点的属性:

prop() 方法和 attr() 类似,对于属性checked处理有所不同:

prop()返回值更合理一些,不过,is()方法判断更好:

类似的属性还有selected,处理时最好用is(':selected')
显示和隐藏DOM
jQuery提供show()和hide()方法:

获取DOM信息

操作表单
对于表单,jQuery对象统一提供val()方法获取和设置对应的value属性:

修改html 结构
-
添加DOM
append()方法,把DOM添加到最后
如:
image.png
列表新增项,首先要拿到<ul>节点,然后调用append()传入html片段:
image.png
image.png
除接受字符串外,append()对象还可以传入原始的DOM对象、jQuery对象和函数对象:
image.png
propend(),把DOM添加到最前
同级节点,可以用after()或者before()
-
删除DOM
拿到jQuery对象后直接调用remove()方法就可以了,如果jQuery包含若干DOM节点,实际上而已一次删除多个节点。
image.png
网友评论