我有以下代码提示用户选择图像:
<div id="frame1" class = "quizFrame quizFrame1">
<p>Which image do you identify with?</p>
<img class = "quizImg" src="images/person1.jpg" alt="" onclick ="ShowNext();" >
<img class = "quizImg" src="images/person2.jpg" alt="" onclick = "ShowNext();">
<img class = "quizImg"src="images/person3.jpg" alt="" onclick = "ShowNext();">
<img class = "quizImg" src="images/person4.jpg" alt="" onclick = "ShowNext();">
</div>
Run Code Online (Sandbox Code Playgroud)
单击图像后,我想确定单击了哪个图像.
有办法以某种方式检索图像的索引吗?(例如,如果单击person1,索引将为0或1)?
我知道我可以为每个图像分配ID,但想知道是否有更简单的路线.
使用Array#indexOf查找所有图片的排列在点击的图像的索引:
var images = [].slice.call(document.querySelectorAll('#frame1 > .quizImg'), 0); // get all images inside frame1, and convert to array
function ShowNext(img) {
console.log(images.indexOf(img)); // find the index of the clicked image inside the array
}Run Code Online (Sandbox Code Playgroud)
<div id="frame1" class = "quizFrame quizFrame1">
<p>Which image do you identify with?</p>
<img class = "quizImg" src="https://placehold.it/60x60" alt="" onclick ="ShowNext(this);" >
<img class = "quizImg" src="https://placehold.it/60x60" alt="" onclick = "ShowNext(this);">
<img class = "quizImg"src="https://placehold.it/60x60" alt="" onclick = "ShowNext(this);">
<img class = "quizImg" src="https://placehold.it/60x60" alt="" onclick = "ShowNext(this);">
</div>Run Code Online (Sandbox Code Playgroud)
或者使用.addEventListener()事件委托:
var frame1 = document.getElementById('frame1'); // find the images container
var images = [].slice.call(frame1.querySelectorAll('.quizImg'), 0); // get all images inside frame1, and convert to array
frame1
// add an event listener that will handle all clicks inside frame1
.addEventListener('click', function(e) {
// find the index of the clicked target from the images array
var index = images.indexOf(e.target)
if(index !== -1) { // if no image was clicked
console.log(index);
}
});Run Code Online (Sandbox Code Playgroud)
<div id="frame1" class = "quizFrame quizFrame1">
<p>Which image do you identify with?</p>
<img class = "quizImg" src="https://placehold.it/60x60" alt="">
<img class = "quizImg" src="https://placehold.it/60x60" alt="">
<img class = "quizImg"src="https://placehold.it/60x60" alt="">
<img class = "quizImg" src="https://placehold.it/60x60" alt="">
</div>Run Code Online (Sandbox Code Playgroud)