我有以下代码:
<div>
<div>
<div>
<div>
<div> I am here </div>
<div> Another div</div>
<div> Find me I am here </div>
</div>
</div>
</div>
</div>
我试图隐藏文本为“Find me I am here”的 div
<script language="t" type="text/javascript">
$(document).ready(function(e) {
$("div:contains('Find me i am here')").css("display","none");
});
</script>
但是上面的代码对我不起作用? 请帮忙。 提前致谢
最佳答案
您还可以在 .each()
中使用 if
条件这样做的方法,甚至比使用 :contains()
更精确,因为 :contains()
会查找该文本,即使它包含另一个字符串,所以它甚至会匹配类似的东西
<div>Hey I don't want to hide this Find me i am here</div>
Ummm you don't need that right? fiddle 的功劳:@Arun P Johny
所以你可以引用下面的解决方案..
$(document).ready(function(e) {
$('div').each(function() {
if($(this).html() == ' Find me i am here ') {
$(this).css({'display': 'none'});
}
});
});
注意:我在if
条件中的字符串前后都有一个空格来进行比较,重要的是,如果你想让它不那么严格,那么使用.trim( )
用于 chop 字符串开头和结尾的空格。
此外,如果您希望定位具有该文本但具有 NO class
或 id
属性的元素,请使用以下代码
$(document).ready(function(e) {
$('div:not([class]):not([id]').each(function() {
//Select only div which doesn't have class or id attributes
if($(this).html() == ' Find me i am here ') {
$(this).css({'display': 'none'});
}
});
});
关于javascript - jQuery,找到没有id没有类但有文本的子div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21201010/