2011-02-12 42 views
1

我有這樣的對象:創建形式從包含對象選擇值

var options = {1: 'Running', 2: 'Falling', 3: 'Collapsing wall', 
     4: (...)}; 

我想創建窗體的選擇元素與此對象採取ooptions,所以類似的東西(代碼我想這是不工作,但你可以得到的想法):

html = '<form action="" ><select name="block-action"><option>-------</option>'; 
for(k in obj){ 
    html += '<option value="'+k+'">'+obj[k]+'</option>' 
} 
html += '</select></form>' 

回答

0
var html = []; // <-- make an array 

//push the first bits of text onto it 
html.push('<form action="" ><select name="block-action"><option>-------</option>'); 

//here's where we dynamically use the object. You were close! You used the wrong variable name, obj vs. options 
for(k in options){ 
    html.push('<option value="'+k+'">',options[k],'</option>'); 
} 

//and wrap up the html tags you opened to start 
html.push('</select></form>'); 

//use html.join(''); to spit out the text 

一般串concats(你在你的例子添加兩個串在一起,像)比推估價要慢得多es放到一個數組上,然後加入它們。我會爲你建議這種習慣。

1

我只能看到的是,你的變量引用的對象稱爲options,但您使用的變量名obj來代替。

在那之後對我有效。

例子:http://jsfiddle.net/X66Su/1/

這樣的:

var options = {1: 'Running', 2: 'Falling', 3: 'Collapsing wall', 
    4: (...)}; 

應該是:

var obj = {1: 'Running', 2: 'Falling', 3: 'Collapsing wall', 
    4: (...)}; 
+0

@ down-voter:小心解釋爲什麼?這個答案如何不正確? – user113716 2011-02-12 23:34:15

+0

該死的,我試圖在控制檯中,並沒有工作。現在就像一個魅力。謝謝:) – marks34 2011-02-12 23:35:19