2

我有以下 JQ 代码:

$("[class^=post],[href='/u1']").prev("div").css("background-color","blue");
$("[class^=post],[href='/u3']").prev("div").css("background-color","red");

示例 HTML:

<div id="container" style="width:500px">
<div id="p1" class="post row1">
    <div class="postprofile" id="profile44" style="height:200px;width:100px;float:left;">
    <dl>
        <dt>
            <a href="/u1"><img src="/logo_1.png" alt=""></a>
            <strong style="font-size:1.2em">
<br />
                <a href="/u1">RD</a>
            </strong>
        </dt>
        <dd>...</dd>
        <dd>...</dd>
    </dl>
    </div>

    <div class="postbody" style="height:200px;width:400px;float:left;">
        <div class="content-clearfix">
            <div>This is a test</div>
        </div>
    </div>  
</div>
</div>

<br />


<div id="container2" style="width:500px">
<div id="p2" class="post row3">
    <div class="postprofile" id="profile45" style="height:200px;width:100px;float:left;">
    <dl>
        <dt>
            <a href="/u3"><img src="/logo_2.png" alt=""></a>
            <strong style="font-size:1.2em">
<br />
                <a href="/u3">Evilyynn</a>
            </strong>
        </dt>
        <dd>...</dd>
        <dd>...</dd>
    </dl>
    </div>
    <div class="postbody" style="height:200px;width:400px;float:left;">
        <div class="content-clearfix">
            <div>This is also a test</div>
        </div>
    </div>

</div>
</div>

我想根据标签中的 href 更改 postprofile div 的背景颜色,以便所有 /u1 href 具有红色背景,所有 /u3 具有蓝色背景等...

据我所知,顶部的 JQ 代码是最容易执行的,但是目前它选择所有类以 post 开头的元素或 /u1 的 href 或 /u3 的 href ,所以当我运行它时postprofile div 具有红色背景。如何让它选择所有以 post AND a href of /u1 开头的类或以 post AND a href of /u3 开头的类

JQ 函数在 HTML 正文加载时被调用。

4

2 回答 2

2

您的问题与您的代码不同,因此我将回答以下问题:

如何让它选择所有以 post AND a href of /u1 开头的类或以 post AND a href of /u3 开头的类

使用选择器上的上下文(第二个参数)来提供上下文。在您的选择器中,传入一个逗号分隔的目标项目列表。

$("a[href='/u1'], a[href='/u3']", "div[class^='post']").closest("div");

小提琴:http: //jsfiddle.net/jonathansampson/FrYF7/

或者,按照您的初始代码:

$("a[href='/u1']").closest("div[class^='post']").css("background", "blue");
$("a[href='/u3']").closest("div[class^='post']").css("background", "red");​

另一种方法是直接进入 div,并从内部执行背景颜色逻辑:

$("div[class^='post']").css("background", function(){
    if ( $("a[href='/u1']", this).length ) { 
        return "blue";
    } else if ( $("a[href='/u3']", this).length ) { 
        return "red";
    }
});​​​
于 2012-06-06T13:55:40.773 回答
0

对于具有多个类的元素,您不需要开始选择器。$("[class^=post]")应该只是$(".post")。此外,,您的选择器中的 将选择两个元素(thea和 the div)。这就是为什么它选择了比预期更多的元素。

使用父母选择器:

$("a[href='/u1']").parents("div.postprofile").css("background-color","blue");
$("a[href='/u3']").parents("div.postprofile").css("background-color","red");
于 2012-06-06T13:58:57.557 回答