2013-03-28 38 views
0

我想在我的.each()之後運行一個單一的.append()以提高效率。我試圖建立我的一套對象,它不會運行。這與這個問題類似,除了我構建一個jQuery對象而不是一個字符串。jQuery.each()構建一組jQuery對象,追加

JQuery append to select with an array

HTML

<select></select>

jQuery的

var items = ['apple','pear','taco','orange'], 
    options = ''; 

jQuery.each(items, function(i, fruit){ 
    options += jQuery('<option/>', { 
     value: fruit, 
     text: fruit 
    }); 
}); //added missing ');' 

jQuery('select').append(options); 

回答

1

你不應該串連對象,你的代碼將導致[object Object][object Object]..。您還缺少)關閉each方法。

$.each(items, function (i, fruit) { 
    options += '<option value=' + fruit + '>' + fruit + '</option>'; 
}); 

$('select').append(options); 

http://jsfiddle.net/NxB6Z/

更新:

var items = ['apple', 'pear', 'taco', 'orange'], 
    options = []; 

jQuery.each(items, function (i, fruit) { 
    options.push($('<option/>', { 
     value: fruit, 
     text: fruit 
    })); 
}); 

jQuery('select').append(options); 

http://jsfiddle.net/HyzWG/

+0

那麼,有沒有辦法做到這一點與對象? –

+0

您不能追加數組。所以這個解決方案不起作用。除非你知道如何讓數組在沒有循環的情況下工作,否則我會採用字符串方法。 –

+0

@ PatrickRobertSheaO'Connor _「你不能追加一個數組」_,這不是真的,它在小提琴中起作用。 – undefined

2

是否需要是一個對象?爲什麼不只是附加到一個字符串,然後追加該字符串?

$.each(items, function(i,fruit){ 
    options += "<option value='"+fruit+"'>"+fruit+"</option>"; 
});