我需要jquery来获取最接近的id,一旦图像可见。到目前为止,这是我的查询
(...)
if(isonscreen)
{
//this works, but I need it to find only images inside the content-bubble div tag
// and of course this grabs any image no matter what div the image is inside of
console.log($(this).closest('img').attr('id'));
}
(...)
<div class="content-bubble">
<h2>{{imageTitle}}</h2>
<img src="loading.gif" id="lazyload{{imgId}}" class="content-bubble-img"">
</div>
我试过了,但它不起作用,并且返回未定义
console.log($(this).closest('.content-bubble-img').find('img').attr('id'));
console.log($('.content-bubble-img').closest('img').attr('id'));
发布于 2014-05-09 16:50:04
我想你需要的是find()
函数,而不是closest()
函数。
发布于 2014-05-09 16:51:23
closest
查找元素最接近的父元素,而find().filter(':first')
查找元素中的第一个子元素。或者用医生的话说:
最近:
对于集合中的每个元素,通过测试元素本身并遍历其在DOM树中的祖先,获取与选择器匹配的第一个元素。
查找:
获取由选择器、jQuery对象或元素过滤的当前匹配元素集中每个元素的后代。
http://api.jquery.com/closest/
http://api.jquery.com/find/
要注释您的代码:
console.log($(this).closest('img').attr('id'));
这实际上很糟糕,因为图像不能有孩子,只有当你使用$(image).closest()
时,closest()
才会返回所选的元素本身,这就是图像。用find
替换closest
,就可以使用了。
发布于 2014-05-09 17:01:49
如果你必须在“content-气泡div”中找到所有图片,而不管图片在哪个div中,那么使用下面的命令:
$('.content-bubble img');
https://stackoverflow.com/questions/23560305
复制相似问题