我有以下 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 和/u1 的 href 开头的所有类或以 post 和/u3 的 href 开头的类
JQ 函数在 HTML 正文加载时调用。
最佳答案
您的问题偏离了您的代码,因此我将回答以下内容:
How do I make it select all classes starting with post AND a href of /u1 or class starting with post AND a href of /u3
使用选择器上的上下文(第二个参数)来提供上下文。在您的选择器中,传入以逗号分隔的目标项列表。
$("a[href='/u1'], a[href='/u3']", "div[class^='post']").closest("div");
fiddle :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";
}
});
关于jquery - 根据子实体中发现的多个条件使用 jQuery 选择 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10915619/