jQuery选择后代,包括父级

编程入门 行业动态 更新时间:2024-10-28 07:29:25
本文介绍了jQuery选择后代,包括父级的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

考虑以下HTML:

<div class="foo" id="obj"> I should be changed red <div class="bar" style="color:black;"> I should not be changed red. <div class="foo">I should be changed red.</div> </div> </div>

给出一个DOM元素obj和一个表达式,我该如何选择任何子级以及可能的obj?我正在寻找与选择后代"相似的东西,但如果它与表达式匹配,则还包括父元素.

Given a DOM element obj and an expression, how do I go about selecting any children and possibly obj? I'm looking for something similar to "select descendants" but also including the parent, if it matches the expression.

var obj = $("#obj")[0]; //wrong, may include siblings of 'obj' $(".foo", $(obj).parent()).css("color", "red"); //wrong -- excludes 'obj' $(".foo", obj).css("color", "red"); //correct way, but it's annoying var matches = $(".foo", obj); if ($(obj).is(".foo")) matches = matches.add(obj); matches.css("color", "red");

是否有更优雅的解决方案?

Is there a more elegant solution to this?

推荐答案

如果我对您的理解正确:

If I understand you correctly:

$(currentDiv).contents().addBack('.foo').css('color','red');

为了清楚起见,我将"div"重命名为"currentDiv".这样会选择当前元素及其包含的所有元素,然后过滤掉不具有类foo的元素,并将样式应用于其余元素,即具有类foo的元素.

I renamed the "div" to "currentDiv" for clarity. This selects the current element and all of the elements it contains, then filters out the ones that do not have class foo and applies the style to the remainder, i.e., the ones that do have class foo.

编辑略微优化

$(currentDiv).find('.foo').addBack('.foo').css('color','red');

编辑

此答案已更新,以合并较新的jQuery方法.原来是

This answer has been updated to incorporate newer jQuery methods. It was originally

$(currentDiv).find('.foo').andSelf().filter('.foo').css('color','red');

1.8之前的jQuery仍然需要

which is still required for jQuery older than 1.8

更多推荐

jQuery选择后代,包括父级

本文发布于:2023-10-26 12:46:46,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1530185.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:后代   jQuery

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!