我试图动态获取正确数组的名称,然后显示该数组的内容。不确定如何执行此操作:
html:
<div class="grid" id="arrSemmes">
<div class="grid-sizer"></div>
<div class="grid-item"><img src="img/2019/s1-thumb.jpg" /></div>
<div class="grid-item"><img src="img/2019/s2-thumb.jpg" /></div>
<div class="grid-item"><img src="img/2019/s3-thumb.jpg" /></div>
<div class="grid-item"><img src="img/2019/s4-thumb.jpg" /></div>
</div>
jquery:
var thisIndex;
var arrSemmes = [
["2019/s1.jpg", "caption1"],
["2019/s2.jpg", "caption2"],
["2019/s3.jpg", "caption3"],
["2019/s4.jpg", "caption4"],
];
$('.grid-item img').on('click', function() {
var thisArray = $(this).parent().parent().attr('id'); //returns a string: arrSemmes
thisIndex = $(this).attr('src');
thisIndex = thisIndex.replace('-thumb.jpg','');
thisIndex = thisIndex.replace('img/2019/s','');
thisIndex = thisIndex--; //must be one less for the array key
alert(thisArray[thisIndex][0]); //thinks I want a letter in the string "thisArray"
});
答案 0 :(得分:0)
简化您的逻辑。使用数据属性并删除基于位置的逻辑。
根据您的评论,我还为上一个和下一个按钮添加了逻辑,使用一个类来标识哪个图像是当前图像,并进行相应调整。
var $images = $('.grid-item img').on('click', function() {
var $img = $(this);
console.log($img.data('src'), $img.data('caption'));
$images.removeClass('current');
$img.addClass('current');
});
function adjustCurrentImage ( adjustment ) {
var currentImageIndex = $images.index($images.filter('.current'));
var nextImageIndex = currentImageIndex + adjustment;
if (-1 < nextImageIndex && nextImageIndex < $images.length) {
$images.removeClass('current');
$images.eq(nextImageIndex).addClass('current');
console.log($images.eq(nextImageIndex).data('src'), $images.eq(nextImageIndex).data('caption'));
}
}
$('#prev').on('click', function(){ adjustCurrentImage(-1); });
$('#next').on('click', function(){ adjustCurrentImage(1); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="grid" id="arrSemmes">
<div class="grid-sizer"></div>
<div class="grid-item"><img src="img/2019/s1-thumb.jpg" data-src="2019/s1.jpg" data-caption="caption1" /></div>
<div class="grid-item"><img src="img/2019/s2-thumb.jpg" data-src="2019/s2.jpg" data-caption="caption2" /></div>
<div class="grid-item"><img src="img/2019/s3-thumb.jpg" data-src="2019/s3.jpg" data-caption="caption3" /></div>
<div class="grid-item"><img src="img/2019/s4-thumb.jpg" data-src="2019/s4.jpg" data-caption="caption4" /></div>
</div>
<button id="prev">Previous Image</button>
<button id="next">Next Image</button>