jQuery选择器是jQuery中的一大特色,它可以方便地将HTML元素选择出来。通过jQuery选择器选择到元素后,我们可以通过后续的遍历方法对元素进行进一步操作,本文将介绍jQuery选择器后遍历的常用方法。

//HTML代码:<ul id="fruit-list"><li class="apple">苹果</li><li class="banana">香蕉</li><li class="orange">橘子</li></ul>//JS代码://选择器选中的元素是li元素var $li = $(li);//parent()方法返回选中元素的直接父元素var $ul = $li.parent();console.log($ul.attr(id));   //输出结果为fruit-list//children()方法返回选中元素的所有子元素,不包括孙元素var $allFruit = $ul.children();console.log($allFruit.length);   //输出结果为3//siblings()方法返回选中元素的兄弟元素,不包括自身var $brothers = $li.siblings();console.log($brothers.length);   //输出结果为2//next()方法返回选中元素的下一个兄弟元素var $nextBrother = $li.next();console.log($nextBrother.html());   //输出结果为香蕉//prev()方法返回选中元素的上一个兄弟元素var $prevBrother = $li.prev();console.log($prevBrother.html());   //输出结果为苹果

以上就是几个常用的jQuery选择器后遍历方法,它们可以在我们操作DOM元素时帮助我们更加方便地操作。

jquery选择器后遍历