创建表单,从包含值的对象中选择
我有这样一个对象:
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>'
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"><option>-------</option>';
for(k in obj){
html += '<option value="'+k+'">'+obj[k]+'</option>'
}
html += '</select></form>'
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我唯一能看到的是引用该对象的变量称为
options
,但您使用的是变量名称obj
。在那次改变之后对我有用。
示例: http://jsfiddle.net/X66Su/1/
这个:
应该是:
Only thing I can see is that your variable referencing the object is called
options
, but you're using the variable nameobj
instead.Works for me after that one change.
Example: http://jsfiddle.net/X66Su/1/
this:
should be:
通常,字符串连接(将两个字符串添加在一起,就像在您的示例中一样)比将值推送到数组然后连接它们要慢得多。我建议你养成这个习惯。
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.