jqueryfilter图像src问题
如果图像包含NO src,那么我想隐藏div.PageHeaderDescription
Bistro 300
This is some text
为此我用过:
if ($("div.PageHeaderDescription img").filter("[src='']")) { $("div.PageHeaderDescription").hide(); }
但是如果你把一个src路径放到图像中,jquery仍然会隐藏div.PageHeaderDescription
,这是错误的。 如果有图像src,它需要是可见的。
这是我的例子: http : //jsfiddle.net/dfasd/1/
filter()
返回一个jQuery对象,无论元素是否匹配,它始终是真实的。
你应该做的是检查返回对象的length
属性;
if ($("div.PageHeaderDescription img").filter("[src='']").length) { $("div.PageHeaderDescription").hide(); }
虽然你可以把它缩短到;
if ($("div.PageHeaderDescription img[src='']").length) { $("div.PageHeaderDescription").hide(); }
但是如果页面上有多个div.PageHeaderDescription
,那么你应该这样做;
$("div.PageHeaderDescription").each(function () { var self = $(this); if (self.find('img[src=""]').length) { self.hide(); } });
$("div.PageHeaderDescription img[src='']").parent().hide();
找到带有空src
并隐藏其父div.PageHeaderDescription
;
DEMO
要么
$("div.PageHeaderDescription").has("img[src='']").hide();
隐藏这个div.PageHeaderDescription
,其中包含img
和空src
。
DEMO
如果要在页面加载时执行此操作,可以使用以下代码:
$("div.PageHeaderDescription img") // search for all img's inside a div... .filter("[src='']") // get only ones with no src .parents("div.PageHeaderDescription") // get their parent elements .hide(); // hide then
或者,每次要检查是否有任何没有src的img都在页面中并且必须隐藏时,您可以运行相同的脚本。
不需要使它比使用.filter()
更复杂。
var phd = $("div.PageHeaderDescription"); if ($('img:not([src])',phd).length || $('img[src=""]',phd).length) { phd.hide(); }
我检查img
是否没有src
属性,或者它是否具有我检查它是否为空的属性。
小提琴: http : //jsfiddle.net/iambriansreed/G6bPu/
如前所述,jQuery对象始终求值为true
。 但是你根本不需要if
语句,只需将元素集减少到具有“空”图像的元素即可。 这就是.filter()
的用途:
$("div.PageHeaderDescription").filter(function() { return $(this).find("img[src='']").length > 0; }).hide();