欢迎各位兄弟 发布技术文章

这里的技术是共享的

You are here

jQuery 遍历 - not() 方法 排除元素 有大用

jQuery 遍历 - not() 方法

实例

从包含所有段落的集合中删除 id 为 "selected" 的段落:

$("p").not("#selected")

亲自试一试

定义和用法

not() 从匹配元素集合中删除元素。

语法 1

.not(selector)
参数描述
selector字符串值,包含用于匹配元素的选择器表达式。

语法 2

.not(element)
参数描述
element一个或多个需要从匹配集中删除的 DOM 元素。

语法 3

.not(function(index))
参数描述
function(index)用于检测集合中每个元素的函数。this 是当前 DOM 元素。

详细说明

如果给定一个表示 DOM 元素集合的 jQuery 对象,.not() 方法会用匹配元素的子集构造一个新的 jQuery 对象。所应用的选择器会检测每个元素;不匹配该选择器的元素会被包含在结果中。

请思考下面这个带有简单列表的页面:

<ul>
  <li>list item 1</li>
  <li>list item 2</li>
  <li>list item 3</li>
  <li>list item 4</li>
  <li>list item 5</li>
</ul>

我们可以向列表项集应用该方法:

$('li').not(':even').css('background-color', 'red');

亲自试一试

这次调用的结果是将项目 2 和 4 设置为红色背景,这是因为它们不匹配选择器(回忆一下,:even 和 :odd 均使用基于 0 的 index)。

移除具体的元素

.not() 方法的第二个版本允许我们从匹配集中删除元素,假设我们之前已经通过其他手段找到了这些元素。例如,设想一个列表已经将 id 应用到其中一个项目中:

<ul>
  <li>list item 1</li>
  <li>list item 2</li>
  <li id="notli">list item 3</li>
  <li>list item 4</li>
  <li>list item 5</li>
</ul>

我们可以使用原生的 JavaScript 函数 getElementById() 读取第三个列表项,然后把它从 jQuery 对象中删除:

$('li').not(document.getElementById('notli')).css('background-color', 'red');

亲自试一试

这条语句改变项目 1、2、3 和 5 的背景色。我们可以用更简单的 jQuery 表达式来完成同样的事情,但是这项技术在比方说其他库提供对纯 DOM 节点的引用时会很有用。

对于 jQuery 1.4,.not() 方法能够采用函数作为其参数,与 .filter() 方法相同。其函数返回 true 的元素会被排除在过滤集之外;所有其他元素将被包含其中。


来自 http://www.w3school.com.cn/jquery/traversing_not.asp



jquery 如何获取某个样式的的 除了第一个之外的所有元素呢

:not(:first)

$(".id:not('.id:first')")

<pre class="brush: javascript">$(“.class:not(‘.class:first’)”)</pre>


来自  https://bbs.csdn.net/topics/391882012


Jquery选择器排除某元素

核心是使用 not 方法

$(".mainTables tr").not("tr:first").click(function(){
});

排除表格的第一行单击

来自  https://blog.csdn.net/c0411034/article/details/53704136

普通分类: