php - jQuery如何将类添加到具有特定类名的第三级子div的父div

标签 php jquery class append

friend 们大家好,我在向我的几个 div 添加特殊类时遇到问题。我的布局是这样的。

<div class="container">
    <div class="grid-6 push-3 equal" style="height: 999px;">
        <div class="block">
            <div id="mainbody"> 
                <!-- Body content here --> 
            </div>
        </div>
    </div>

    <div class="grid-2 equal" style="height: 999px;">
        <div class="block">
            <div id="sidebar-a"> 
                <!-- Sidebar-a content here --> 
            </div>
        </div>
    </div>

    <div class="grid-2 equal" style="height: 999px;">
        <div class="block">
            <div id="sidebar-b"> 
                <!-- Sidebar-b content here --> 
            </div>
        </div>
    </div>

    <div class="grid-2 equal" style="height: 999px;">
        <div class="block">
            <div id="sidebar-c"> 
                <!-- Sidebar-c content here --> 
            </div>
        </div>
    </div>
</div>

我想通过 CSS 向每个侧边栏添加不同的背景颜色,当我编写如下代码时:

#mainbody { background : #fff; }
#sidebar-a { background : #eee; }
#sidebar-b { background : #ddd; }
#sidebar-c { background : #ccc; }

它仅将背景应用于该特定类,但该特定类的高度不相等。我实际上需要申请这个<div class="grid-2 equal" style="height: 999px;">分区。

现在的问题是在这个

<div class="grid-6 push-3 equal" style="height: 999px;"><div class="grid-2 equal" style="height: 999px;">

类名grid-6grid-2是由我的 960 Grid System 的 PHP 以及 style="height: 999px; 动态生成的由 Equal-Columns 的 jQuery 脚本生成。

我想要的是像这样添加一个唯一的类名......找个divclass.equal其中有 child divclass.block并且进一步具有 child divIDsidebar-a

如果为 TRUE,则添加 class.sidebar-a转到主div其中有 class.equal

结果如下所示:

<div class="grid-6 equal push-3 mainbody" style="height: 999px;">
<div class="grid-2 equal sidebar-a" style="height: 999px;">
<div class="grid-2 equal sidebar-b" style="height: 999px;">
<div class="grid-2 equal sidebar-c" style="height: 999px;">

然后我就可以像这样设置它的样式:

.mainbody { background : #fff; }
.sidebar-a { background : #eee; }
.sidebar-b { background : #ddd; }
.sidebar-c { background : #ccc; }

因此我想既然我在模板中使用了 jQuery,为什么不使用它来处理这个问题呢?如果您还有其他想法,请随时提出更好的方法。

最佳答案

您可以在标准 jQuery 选择器中执行选择逻辑,然后对于您发现的每个侧边栏,在 DOM 树中向上查找具有类 equal 的第一个 div,并使用每个侧边栏 ID 的名称:

$('div.equal div.block div[id^="sidebar"]').each(function() {
    $(this).closest('div.equal').addClass(this.id);
});

关于php - jQuery如何将类添加到具有特定类名的第三级子div的父div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4630620/

相关文章:

javascript - 如何将多个 Jquery ID 传递给一个函数?

javascript - 获取事件日期

jquery添加类问题

php - php中的3级数组用于组织数据

java - 如何? - 在同一文件执行 GET 之前将字符串插入 php 文件

php - 为什么我需要一个电子邮件帐户才能在 ruby​​ 上发送邮件而在 php 上不需要这样的帐户?

jquery - Struts Jquery插件: Remote Dialogs With Parameters

php - 如何在每个循环中增加 Jquery 变量

php - 这是执行此 PHP 类的正确方法吗?

c++ - 如何修复通过重载和模板化的插入运算符尝试显示字符串对象数组而产生的空白输出?