我要尝试的是单击文本时,如果另一个div有一个包含此文本的子项淡入,但是它不起作用
$('.rel-head').click(function() {
if ($('.art-h .head-art'): contains($(this).text())) {
$(this).parent().fadeIn().siblings().fadeOut();
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="art-h">
<div class="head-art">some text</div>
</div>
<div class="art-h">
<div class="head-art">anoter text</div>
</div>
<div class "related-heads">
<h1 class="rel-head">some text</h1>
</div>
答案 0 :(得分:1)
:contains
并正确连接字符串。
$('.rel-head').click(function() {
if ($('.art-h .head-art:contains('+$(this).text()+')')) {
$(this).parent().fadeIn().siblings().fadeOut();
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="art-h">
<div class="head-art">some text</div>
</div>
<div class="art-h">
<div class="head-art">anoter text</div>
</div>
<div class "related-heads">
<h1 class="rel-head">some text</h1>
</div>
答案 1 :(得分:0)
每次单击每个指定项目时搜索整个身体并不是很有效。
这就是我要做的。
let headArtArray = $('.art-h .head-art'); //Assign it to a variable early to reduce searching
$('.rel-head').click(function() {
let el = $(this);
let text = el.text();
for (let i = 0; i < headArtArray.length; i++) {
if (headArtArray[i].innerText.includes(text)) {
el.parent().fadeIn();
} else {
$(headArtArray[i]).fadeOut();
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="art-h">
<div class="head-art">some text</div>
</div>
<div class="art-h">
<div class="head-art">anoter text</div>
</div>
<div class "related-heads">
<h1 class="rel-head">some text</h1>
</div>