jQuery 过滤
jQuery 遍历:过滤选择集
Section titled “jQuery 遍历:过滤选择集”通常,在选中一组元素或遍历 DOM(文档对象模型)之后,你需要进一步缩小选择范围。jQuery 为此提供了几种过滤方法。
基于位置的基本过滤
Section titled “基于位置的基本过滤”这些方法根据元素在匹配集合中的位置来选择元素:
jQuery first() 方法
Section titled “jQuery first() 方法”将匹配的元素集合减少到只剩下集合中的第一个元素。
示例:选择页面上的第一个列表项 (<li>)。
$(function() { // 获取所有列表项,然后过滤出第一个 const firstItem = $("li").first(); firstItem.css('font-weight', 'bold'); // 样式化第一个列表项});jQuery last() 方法
Section titled “jQuery last() 方法”将匹配的元素集合减少到只剩下集合中的最后一个元素。
示例:选择特定 <div> 内的最后一个段落 (<p>)。
$(function() { // 查找 #content 内的段落,然后过滤出最后一个 const lastPara = $("div#content p").last(); lastPara.css('font-style', 'italic'); // 样式化最后一个段落});jQuery eq() 方法
Section titled “jQuery eq() 方法”将匹配的元素集合减少到指定索引位置的那个元素。记住索引是从零开始的(第一个元素的索引是 0,第二个是 1,依此类推)。
示例:选择页面上的第二个段落 (<p>)(索引为 1)。
$(function() { // 获取所有段落,然后选择索引为 1 的那个 const secondPara = $("p").eq(1); secondPara.css('color', 'blue'); // 样式化第二个段落});使用负数索引与 eq() 方法会从集合末尾开始倒数(例如,eq(-1) 等同于 last(),eq(-2) 选择倒数第二个)。
基于内容的过滤
Section titled “基于内容的过滤”这些方法根据元素是否符合特定条件来过滤元素:
jQuery filter() 方法
Section titled “jQuery filter() 方法”将匹配的元素集合减少到只保留那些匹配提供的选择器或在提供的函数中通过测试的元素。
示例:从所有段落中,只选择带有类名 MuiDialog-paper 的段落。
$(function() { // 获取所有段落,然后过滤,只保留带有类名 ' MuiDialog-paper' 的段落 const importantParas = $("p").filter(". MuiDialog-paper"); importantParas.wrap("****"); // 包装重要的段落});使用函数的示例:选择宽度大于 100px 的图像。
$(function() { const largeImages = $("img").filter(function() { // 'this' 指的是迭代中的当前 img 元素 return $(this).width() > 100; }); largeImages.css('border', '2px solid red');});jQuery not() 方法
Section titled “jQuery not() 方法”从匹配的元素集合中移除元素。它是 filter() 的反向操作。
示例:从所有列表项中,选择那些 不 带有类名 active 的列表项。
$(function() { // 获取所有列表项,然后移除带有类名 'active' 的那个 const inactiveItems = $("li").not(".active"); inactiveItems.css('opacity', 0.5);});和 filter() 一样,not() 也可以接受一个函数作为参数。
jQuery has() 方法
Section titled “jQuery has() 方法”将匹配的元素集合减少到只保留那些包含匹配提供的选择器的后代元素的元素。
示例:只选择包含 <span> 元素的列表项 (<li>)。
$(function() { // 获取所有列表项,然后过滤,只保留包含 span 的那些 const itemsWithSpan = $("li").has("span"); itemsWithSpan.addClass('has-details');});jQuery 遍历参考
Section titled “jQuery 遍历参考”有关所有 jQuery 遍历和过滤方法的完整概览,请查阅官方 jQuery API 文档。