jquery - 根据子实体中发现的多个条件使用 jQuery 选择 div

标签 jquery html selection criteria

我有以下 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/

相关文章:

javascript - CORS 在 jquery 中工作正常但在 angularjs 中不工作

javascript - 列出选定类别和价格范围内的产品

javascript - HTML 中的 TABS : Select first TAB by default

python - Matplotlib:用鼠标画出矩形形状的选区

javascript - 如何查找表格列宽并应用于同一页面中的另一个表格

javascript - jQuery 图像旋转

javascript - 输入图片中的文字

html - 为什么使用属性固定元素会改变它的大小?

vba - Selection 或 ActiveRange 可以是可选参数吗?

javascript - 选择 HTML 元素中的一部分文本