[英]How to find the position of the certain element inside a div?
我想在我的div中找到图像位置
我的Html
<div>
<p>test</p>
<img src='test1.jpg'/>
<p>test</p>
<p>test</p>
<img src='test2.jpg'/>
<p>test</p>
<img src='test2.jpg'/> --the user clicks this image and I want to know the time it appears. In this case, 2 is what I need.
<p>test</p>
<img src='test2.jpg'/>
<p>test</p>
</div>
我有
var imagePosition=0;
$('img').click(function(){
var imgSource=$(this).attr('src');
$(this).closest('div').find('img').each(function(){
if($(this).attr('src')==imgSource){
imagePosition++;
}
})
})
我可以找出相同图像出现的时间,但我无法分辨用户点击的图像和位置。 反正有没有这样做? 非常感谢!
$('img').click(function() {
var clickedIndex = $('img[src="'+ $(this).attr('src') +'"]').index(this) + 1;
console.log(clickedIndex);
});
在这里,我构建了一个属性搜索图像,其属性与被点击的图像相同,然后调用.index(element)
将点击的元素作为参考传递。 由于index
是从0开始的 ,我们加1。
如果拥有相同的祖先div
是重要的,只需使用closest
东西进行调整并find
最初的:
var clickedIndex =
$(this).closest('div')
.find('img[src="'+ $(this).attr('src') +'"]').index(this) + 1;
要获得对单击图像的引用,只需在处理程序中使用this
关键字。 你可以将它包装在一个jQuery对象$(this)
,然后在它上面调用jQuery方法。
另外,通过你的问题的代码注释,我假设你的position
你实际上是指元素的index
,但如果你想获得元素的文字位置,你可以使用.offset()
(相对于文档)和.position()
(相对于父)方法。
侧注:如果需要计算具有相同源的图像数量,可以使用.length
以更简单的方式完成:
var countImages = $('img[src="'+ $(this).attr('src') +'"]').length;
同样,上面假设它位于事件处理程序的范围内,其中this
引用了一个图像元素。 您可以轻松地调整它以查询任何src
。
您可以使用索引
$('img').click(function(){
index = $(this).closest('div').find('img').index(this) + 1;
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.