2013-05-01 81 views
1

如何使用JQuery在HTML代码中搜索?我想在HTML代码中找到一个字符串,然后隐藏div。这不起作用:在HTML代码中搜索?

<div class="example"> 
test 
<img src="example.jpg"></div> 
$(document).ready(function(){ 
    $(".example:contains('example.jpg')").hide(); 
}); 

但是,当我告诉它来搜索“测试”,而不是“example.jpg”,它的工作?

+4

:包含搜索文本内容,而不是在孩子的属性内容元素。 – 2013-05-01 20:35:03

+0

然后有HTML选择器吗?我试过.attr()并且不起作用。 – user2338015 2013-05-01 20:35:51

+1

'$('[src =“example.jpg”]')'会做到这一点 – Blazemonger 2013-05-01 20:36:14

回答

1
$('img[src="example.jpg"]').parent().hide(); 

但是,这是非常紧密的代码,你应该更好地设计你的标记来处理它。

0

尝试以下

$(document).ready(function(){ 
if($('.example').html().indexOf('example.jpg')!=-1){ 
$('.example').hide(); 
} 
}); 
+0

为了未来用户的利益,你可以考虑解释_why_。 – Ben 2013-05-01 20:57:42

2

合并:hasattribute-equals选择。

$('.example:has([src="example.jpg"])').hide(); 

http://jsfiddle.net/J9bgt/

这会更有效,因为这样的事实::has是jQuery的实现了自定义选择:

$('.example').filter(':has([src="example.jpg"])').hide();