欢迎来到飞鸟慕鱼博客,开始您的技术之旅!
当前位置: 首页前端设计正文

jQuery中parent(),parents()和closest()详解与区别

墨初 前端设计 4542阅读

这篇文章主要为记录一个JQ中的三个方法的解释和区分,不再做安例演示,因为今天有点懒,啥也不想做,班也不想上!

jQuery 遍历 - parent() 方法

parent() 方法:获得指定元素的父元素

语法:

.parent(selector)

注:selector为包含用于匹配元素的选择器表达式,可省略

例:

jQuery中parent(),parents()和closest()详解与区别

HTML代码:

<div>
    <p>我是第一个DIV的P标签</p>
</div>
<div class="mochu">
    <p>我是第二个DIV的P标签</p>
</div>

JQ代码

$("p").parent(".mochu").css("color","red");

jQuery 遍历 - parents() 方法

parents() 方法:获得指定元素的祖元素

语法:

.parents(selector)

注:selector为包含用于匹配元素的选择器表达式,可省略

jQuery 遍历 - closest() 方法

closest() 方法获得匹配选择器的第一个祖先元素,从当前元素开始沿 DOM 树向上。

语法:

.closest(selector)

注:selector为包含用于匹配元素的选择器表达式,可省略

声明:无特别说明,转载请标明本文来源!