JQuery.each()函数中元素的长度

JQuery.each()函数中元素的长度,jquery,Jquery,假设我有以下HTML <div class="news_item"> <div class="news_content">Some Content Here...</div> <img src="something.jpg" /> </div> 但是$('img',this).length在每个函数中似乎都不起作用。尝试$(this.find('img')。length您的代码仍然很好。请确保您没有无效的HTML,或者

假设我有以下HTML

<div class="news_item">
    <div class="news_content">Some Content Here...</div>
    <img src="something.jpg" />
</div>

但是$('img',this).length在每个函数中似乎都不起作用。

尝试
$(this.find('img')。length
您的代码仍然很好。请确保您没有无效的HTML,或者没有错误地查找并在同级元素中发现图像。

这听起来好像正常,但这里有一些替代代码,可以过滤掉img子元素中的任何div

$('div.news_item').not(function(index){return $(this).find('img').length > 0;}).each(function(index, elem){
     $(this).css('background-color', '#cccccc');
});

当我在JSFIDLE中测试它时,它似乎可以工作-您使用的是什么浏览器?我使用的是firefox。感谢各位的回复,我将不得不再次检查这个。嗯,奇怪的是,我将检查我的HTML。关于
$(这个)。儿童(“img”)。长度
?儿童只会深入一层,找到所有层次的钻取是的,但它在
每个
中,所以,每个
div.new\u项目
中都有一层深度。另外,这取决于DOM,但在这种情况下,子对象可能更有效。如果只在直接子对象中查找图像,则
子对象
将更有效。依赖于dom
$('div.news_item').not(function(index){return $(this).find('img').length > 0;}).each(function(index, elem){
     $(this).css('background-color', '#cccccc');
});