I have such an object :
var options = {1: 'Running', 2: 'Falling', 3: 'Collapsing wall',
4: (...)};
I'd like to create form's select element with ooptions taken from this object, so something like that (code I tried which is not working, but you can get the idea) :
html = '<form action="" ><select name="block-action">&l开发者_Python百科t;option>-------</option>';
for(k in obj){
html += '<option value="'+k+'">'+obj[k]+'</option>'
}
html += '</select></form>'
Only thing I can see is that your variable referencing the object is called options
, but you're using the variable name obj
instead.
Works for me after that one change.
Example: http://jsfiddle.net/X66Su/1/
this:
var options = {1: 'Running', 2: 'Falling', 3: 'Collapsing wall',
4: (...)};
should be:
var obj = {1: 'Running', 2: 'Falling', 3: 'Collapsing wall',
4: (...)};
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
Generally string concats (where you add two strings together, like in your example) are much slower than pushing values onto an array and then joining them. I'd suggest that habit for you.
精彩评论