jQuery - 选择同一级别的子级(奇数或偶数)

发布于 2024-08-14 05:34:50 字数 329 浏览 3 评论 0原文

有没有办法用 jQuery 替换下面的 CSS?

.quote-body .quote-body { background: #f5f5f5 }
.quote-body .quote-body .quote-body { background: #fff }
.quote-body .quote-body .quote-body .quote-body { background: #f5f5f5 }
.quote-body .quote-body .quote-body .quote-body .quote-body { background: #fff }
...
and so on

is there a way to replace following CSS with jQuery?

.quote-body .quote-body { background: #f5f5f5 }
.quote-body .quote-body .quote-body { background: #fff }
.quote-body .quote-body .quote-body .quote-body { background: #f5f5f5 }
.quote-body .quote-body .quote-body .quote-body .quote-body { background: #fff }
...
and so on

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

戴着白色围巾的女孩 2024-08-21 05:34:50

这样的方法可能有效:

$('.quote-body').each(function() {
    $(this).addClass($(this).parents('.quote-body').size() % 2 ? 'odd' : 'even');
});

对于每个 .quotebody 元素,查找具有 .quotebody 类的父元素的数量,并取模 2 来定义奇数或偶数。

编辑

经过测试并且运行良好。对于复杂的文档,此方法可能有点缓慢,因为对于每个元素,jQuery 都必须遍历回根元素。但它有效。

工作示例: http://www.ulmanen.fi/stuff/oddevenchild.php

Something like this might work:

$('.quote-body').each(function() {
    $(this).addClass($(this).parents('.quote-body').size() % 2 ? 'odd' : 'even');
});

For every .quotebody element, find the number of parent elements that has the class .quotebody and take modulo of two to define odd or even.

EDIT

Tested and working beautifully. This method might be a bit sluggish on complicated documents as for every element, jQuery has to traverse all the way back to the root element. But it works.

Working example: http://www.ulmanen.fi/stuff/oddevenchild.php

停顿的约定 2024-08-21 05:34:50

我想不出可以解决此问题的简单选择器,但您也许可以使用 while 循环来实现预期结果:

var $quotes = $(<containing-elem>).children(".quote-body"), level = 0;

while($quotes.length > 0) {
    $quotes.css("background-color", (level % 2 ? "#f5f5f5" : "#fff"));
    level += 1;
    $quotes = $quotes.children(".quote-body");
}

确保您最初不会选择太多 .quote-body 元素,我首先选择作为包含元素的直接子元素的 .quote-body 元素。

I can't think of a simple selector that could solve this, but you may be able to achieve the intended results using a while loop:

var $quotes = $(<containing-elem>).children(".quote-body"), level = 0;

while($quotes.length > 0) {
    $quotes.css("background-color", (level % 2 ? "#f5f5f5" : "#fff"));
    level += 1;
    $quotes = $quotes.children(".quote-body");
}

To ensure that you don't initially select too many .quote-body elements, I'm first selecting the .quote-body elements that are immediate children of the containing element.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文