[英]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);
如果我理解正确,则不需要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.