jQuery:has()和jQuery:contains()区别

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了jQuery:has()和jQuery:contains()区别相关的知识,希望对你有一定的参考价值。

jQuery:has()和jQuery:contains()两个方法比较类似。不同点在于:

has是判断标签的

contains是判断文本的

1、jQuery:has()

<div><p>Hello</p></div>

<div>Hello again!</div>

$("div:has(p)").addClass("test");

//含有p标签的div标签增加test样式

注:has中的括号里可以含引号也可以省略。

2、jQuery:contains()

<div>John Resig</div>

<div>George Martin</div>

<div>Malcom John Sinclair</div>

<div>J. Ohn</div>

$("div:contains(‘John‘)").addClass(‘test‘);

//给含有John文本的div标签增加test样式

注:contains中的括号里可以含引号也可以省略。

3、jQuery:empty

<div></div>

<div><span></span></div>

<div>span</div>

$(‘div:empty‘).addClass(‘test‘);

//给不含任何文本并且不含任何标签的div增加样式test

注:empty没有括号。

以上是关于jQuery:has()和jQuery:contains()区别的主要内容,如果未能解决你的问题,请参考以下文章