簡體   English   中英

檢查(如果)並在jQuery中選擇孩子/父母

[英]checking (if) and selecting children/parent in jquery

我的html:

<div class="red-box">
<h2>
<a href="#">My Cars</a>
</h2>

<div class="block_left layout2">
    <div class="part1">
        <div class="gallery_block">
            <div class="block_topic">1</div>
            <div class="block_topic">2</div>
            <div class="block_topic">3</div>
        </div>
    </div>
</div>

<div class="red-box">
<h2>
<a href="#">My Bikes</a>
</h2>

<div class="block_left layout2">
    <div class="part1">
        <div class="gallery_block">
            <div class="block_topic">1</div>
            <div class="block_topic">2</div>
            <div class="block_topic">3</div>
        </div>
    </div>
</div>

</div>....

像上面的示例一樣, <h2><a href="">TITLE</a></h2>中有很多帶有不同標題的“紅色框” div。 而且我只需要選擇和更改一個-“紅色框”->“ block_left”->“ part1”->“ gallery_block”->“ block_topic”,其中包含“ 3”,並且只能在單個“紅色框”中執行”,其中<h2><a href="">My Cars</a></h2>

因此,我正在執行以下操作:

    if ($(".red-box").children("h2").children("a").children("span:contains('My Cars')").length > 0) 
    {
// it finds the "red-box" which i need but how to select
// <div class="block_topic">3</div> in the "red-box" whose href has "My Cars"?
}

謝謝

$('.red-box').has('h2:contains(My Cars)').find('div.block_topic').eq(2);

http://jsfiddle.net/L5YBf/1/

使用.has() :contains ..

嘗試這個

$('.red-box').has('h2:contains("My Cars")').find('div.block_topic:contains("3")');

$('.red-box').has('h2:contains("My Cars")') =>獲取包含“ My cars”的.red-box。

.find('div.block_topic:contains("3")') =>查找div.block_topic包含3

如果我理解正確,則不需要if()表達式,而只是適當措辭的jQuery選擇表達式。

另外,尤其是要對表達式進行泛化時,應避免:contains ,這是不加區別的,因為它將找到具有與感興趣的字符串匹配的嵌入子字符串的元素。

要選擇文本完全匹配的元素,可以使用.filter() ,如下所示:

$(".red-box h2 a").filter(function() {
    return $(this).text() === 'My Cars';
}).closest(".red-box").find(".block_topic").filter(function() {
    return $(this).text() === '3';
});

或者,如果您想要一個已知索引的.block_topic

$(".red-box h2 a").filter(function() {
    return $(this).text() === 'My Cars';
}).closest(".red-box").find(".block_topic").eq(2);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM