2013-05-01 77 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();