2013-10-01 43 views
0

我想要在select標記中獲得options的數量,然後從中生成相同數量的圖像路徑。Javascript/jQuery - 使用基於變量索引的數組<option>

​​
+1

你要創建一個字符串,而不是一個數組。使用'for'循環或'$ .map()'。 –

+0

@PSL我用你的解決方案,但我很好奇Satpal的解決方案如何在性能上堆積如山。注意,我的其他一些相關腳本現在似乎已停止工作。所以我目前正處於十字路口。 – stephenway

回答

1

您可以通過有環和創建像

$images = []; 
for (var i=1;i<= $optionIndex ;i++) 
{ 
    $images.push(imagePath + i + ".jpg"); 
} 

Demo

+0

我最終使用這個性能http://jsperf.com/array-vs-for – stephenway

1

一個數組的事情是$("option", "select").index$("option", "select").index()。否則,您將最終得到index方法的函數引用。但是我想你想要這個長度然後迭代。

但在這裏,你可以這樣做:

var $imagePathArray = $("select").find("option").map(function(i){ //<-- zero based index 
     return imagePath + i + ".jpg" ; 
}).get(); 

Demo

0

試着這麼做:

var selOps = $('#selectId>option'), imagePath = '/images/slider/slide-', imgs = []; 
selOps.each(function(i){ 
    imgs[i] = imagePath+this.val()+'.jpg'; 
}); 
$(window).load(function(){ 
    var $slider = $(".slider").slider({ 
    // not sure there is an images property of the slider object, so I'm confused about this part 
    }); 
});