[英]How can I make this code efficient by looping?
我正在嘗試提取圖像以在li元素上顯示為背景圖像。
li的確切數目是不確定的,但是我的代碼在處理此問題方面效率不高,因為我不得不手動將其寫入。我不確定最好的循環方法,以便在添加更多li時不需要手動處理。
$('.carousel').each(function(){
var i = 0;
$(this).find("li").each(function(){
i++;
$(this).addClass('thumbnail'+i);
});
$(this).find("li.thumbnail1").css('background-image', 'url(' + $(this).find('.item:nth-child(1) img').attr('src') + ')');
$(this).find("li.thumbnail2").css('background-image', 'url(' + $(this).find('.item:nth-child(2) img').attr('src') + ')');
$(this).find("li.thumbnail3").css('background-image', 'url(' + $(this).find('.item:nth-child(3) img').attr('src') + ')');
$(this).find("li.thumbnail4").css('background-image', 'url(' + $(this).find('.item:nth-child(4) img').attr('src') + ')');
$(this).find("li.thumbnail5").css('background-image', 'url(' + $(this).find('.item:nth-child(5) img').attr('src') + ')');
});
var that = this;
$(this).find("li").each(function(index){
var imgSrc = $(that).find('.item:nth-child(' + (index+1) + ') img').attr('src');
$(this).css('background-image', 'url(' + imgSrc + ')');
});
我認為這比您正在做的事情更有意義。 jQuery .each函數將Index作為第一個參數,因此如果需要,您可以找到具有相同索引的匹配.item
使用$ .each()函數時,可以向其傳遞一些參數。 例如:
$(this).find("li").each(function(i, o){ });
其中i是索引,而o是對象本身(在您的情況下為li元素)。 因此,您可以嘗試執行以下操作:
$(this).find("li.thumbnail" + i).css('background-image', 'url(' + $(this).find('.item:nth-child('+ (i - 1) + ') img').attr('src') + ')');
像這樣重寫它會更有效率。
$('.carousel').each(function(){
var $carousel = $(this);
$carousel.find("li").each(function(index){
$(this).addClass('thumbnail'+index);
$(this).css('background-image', 'url(' + $carousel.find('.item:nth-child(index) img').attr('src') + ')');
});
});
存儲輪播的each()
允許您在li
的each()
范圍內與其進行交互。 無需聲明單獨的i
變量,因為在對each()
的調用中傳遞給函數的第一個參數是當前項目的索引。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.