2010-12-21 71 views
25

上午所有,找到图片src:包含?

我有图像的列表,像这样:

<ul id="preload" style="display:none;"> 
<li><img src="afx4000z-navy-icon-1_thumb.jpg"/></li> 
<li><img src="afx4000z-green-icon-1_thumb.jpg"/></li> 
</ul> 

使用jQuery如何找到UL#预紧内的所有图片src的含有特定字符串,例如“绿色”

。像...

var new_src = jQuery('#preload img').attr('src')*** that contains green ***; 

回答

51

您需要使用the *= selector

jQuery('#preload img[src*="green"]') 

如果你希望它是区分大小写的,这将是一个有点难度:

var keyword = "green"; 
$("#preload img").filter(function(keyword) { 
    return $(this).attr("src").toLowerCase().indexOf(keyword.toLowerCase()) != -1; 
}); 
+0

非常感谢Gabi!完美的作品! – 2010-12-21 10:44:51

+0

你的第二个例子会抛出一个错误,数字没有'.toLowerCase()'方法。 – 2010-12-21 11:26:38

+2

我怎样才能用这个逻辑找出所有没有绿色的图像? – dubbs 2014-06-19 09:29:34

10

您可以使用attribute-contains selector[attr*=value]),像这样:

jQuery('#preload img[src*=green]') 
+2

错误。 '绿色'应该在引号中。从链接:“行情是强制性的。” – 2010-12-21 10:28:13

+1

可爱,是否区分大小写?猜猜它会是...我怎样才能使用它不区分大小写? – 2010-12-21 10:28:53

+1

@Gabi - 它们不是必需的,请自己测试...只有当值包含任何特殊字符时才需要它们。 – 2010-12-21 11:24:11