function openGallery(){
console.log($(this).index());
}
$("body").on( "click", "#gallery img", openGallery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section class="grid-x grid-padding-x section-content" id="gallery">
<div class="cell small-12">
<h1>Gallery</h1>
</div>
<div class="cell small-12">
<section class="grid-x grid-padding-x small-up-2 medium-up-4 large-up-6">
<div class="cell"><img src="img/gallery/gallery-1-sm.jpg" alt="gallery 1"></div>
<div class="cell"><img src="img/gallery/gallery-2-sm.jpg" alt="gallery 2"></div>
<div class="cell"><img src="img/gallery/gallery-3-sm.jpg" alt="gallery 3"></div>
<div class="cell"><img src="img/gallery/gallery-4-sm.jpg" alt="gallery 4"></div>
<div class="cell"><img src="img/gallery/gallery-5-sm.jpg" alt="gallery 5"></div>
<div class="cell"><img src="img/gallery/gallery-6-sm.jpg" alt="gallery 6"></div>
</section>
</div>
</section>
//我一直得到0作为点击内容的索引谷。我想我错过了很简单的事情。
答案 0 :(得分:4)
为$(this).index()
$(this).index('img')
有关使用jQuery
.index()
函数Click Here
function openGallery() {
console.log($(this).index('img'));
}
$(document).on("click", "#gallery img", openGallery);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section id="gallery">
<div class="cell"><img src="img/gallery/gallery-1-sm.jpg" alt="gallery 1"></div>
<div class="cell"><img src="img/gallery/gallery-2-sm.jpg" alt="gallery 2"></div>
<div class="cell"><img src="img/gallery/gallery-1-sm.jpg" alt="gallery 1"></div>
<div class="cell"><img src="img/gallery/gallery-1-sm.jpg" alt="gallery 1"></div>
<div class="cell"><img src="img/gallery/gallery-1-sm.jpg" alt="gallery 1"></div>
<div class="cell"><img src="img/gallery/gallery-1-sm.jpg" alt="gallery 1"></div>
</section>
&#13;
如果您有任何疑问,请在下面留言,我会尽快给您回复。
我希望这有帮助,快乐编码!
答案 1 :(得分:0)
每个图像都在它自己的div中,因此每个图像都有一个兄弟列表,只有一个元素(本身),这就是索引始终为零的原因。这可行:
function openGallery(){
console.log($(this).parent().index());
}
答案 2 :(得分:0)
它始终为零,因为每个单元格中只有1 <img>
,显然它们都是索引零。如果您希望索引更好地将点击事件监听器放在.cell
上,或者您可以在每个id
标记中放置唯一的<img>
。