我正在使用AJAX调用Flickr JSON文件来引入我的所有照片数据。然后数据通过每个循环运行,其中收集变量,然后用于连接每张照片的字符串并将其写入自定义灯箱。
对于灯箱,我使用this W3 lightbox tutorial作为照片的容器。
我的问题是如何创建一个数字变量并将其分配给每个循环中的对象,以便我可以创建这样的东西:
onclick="openModal();currentSlide(foo)"
例如,如果我的每个循环中有5个对象,我希望每个循环都分配一个以1开头并增加到5的变量。
//Call all images from Flickr
var photoSettings = {
"async": true,
"crossDomain": true,
"url": "https://api.flickr.com/services/rest/?method=flickr.photos.search&...&format=json&nojsoncallback=1",
"method": "GET",
"headers": {}
}
$.ajax(photoSettings).done(function (data2) {
$.each( data2.photos.photo, function( i, gp ) {
var farmId2 = gp.farm;
var serverId2 = gp.server;
var id2 = gp.id;
var secret2 = gp.secret;
var title2 = gp.title;
var description2 = gp.description._content;
$('.flickrContain').on('click', function() {
if ($(this).attr('alt') == '2017—Yonge St., Richmond Hill'){
if ((title2.indexOf( 'Y2' )> -1) && (title2.indexOf( '2017' )> -1)){
var foo = assign a number to each of the conditional objects
//main image slider
$('.image-slider').append('<div class="mySlides"><img src="https://farm' + farmId2 + '.staticflickr.com/' + serverId2 + '/' + id2 + '_' + secret2 + '.jpg" width="100%" alt="' + description2 + '" title="' + description2 + '" id="H2BandC-2017-' + id2 + '"/></div>');
//thumnails
$('.image-list').append('<li class="flickrSliderImg"><a href="#H2BandC-2017-' + id2 + '"><img class="demo" src="https://farm' + farmId2 + '.staticflickr.com/' + serverId2 + '/' + id2 + '_' + secret2 + '.jpg" alt="' + description2 + '" title="' + description2 + '" width="160px" height="90px" border="0" onclick="currentSlide(' + foo + ')"/></a></li>');
};
} else if ($(this).attr('alt') == '2016—Yonge St., Richmond Hill'){
if ((title2.indexOf( 'Y2' )> -1) && (title2.indexOf( '2016' )> -1)){
var foo = assign a number to each of the conditional objects
//main image slider
$('.image-slider').append('<div class="mySlides"><img src="https://farm' + farmId2 + '.staticflickr.com/' + serverId2 + '/' + id2 + '_' + secret2 + '.jpg" width="100%" alt="' + description2 + '" title="' + description2 + '" id="H2BandC-2016-' + id2 + '"/></div>');
//thumnails
$('.image-list').append('<li class="flickrSliderImg"><a href="#H2BandC-2016-' + id2 + '"><img class="demo" src="https://farm' + farmId2 + '.staticflickr.com/' + serverId2 + '/' + id2 + '_' + secret2 + '.jpg" alt="' + description2 + '" title="' + description2 + '" width="160px" height="90px" border="0" onclick="currentSlide(' + foo + ')"/></a></li>');
}
}
});
});
});
答案 0 :(得分:0)
从docs您可以看到,当您致电each
时,您可以为传递给它的功能定义index
参数:
jQuery.each( arr, function( index, val ) {
$( "#" + val ).text( "Mine is " + val + "." );
// Will stop running after "three"
return ( val !== "three" );
});
答案 1 :(得分:0)
感谢@LajosArpad!您向正确的方向发送了我。以下代码可以将缩略图的索引值放置在currentSlide();
$('img.demo').each(function (index){
$(this).attr('onclick', 'currentSlide(' + index + ')');
});
我还将上面的.append代码重写为:
.append('...onclick=""...')