使用jQuery作为JS对象向select中添加选项的最佳方法是什么? [英] What is the best way to add options to a select from as a JS object with jQuery?

查看:108
本文介绍了使用jQuery作为JS对象向select中添加选项的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用jQuery从JavaScript对象向< select> 添加选项的最佳方法是什么?



<我正在寻找一些我不需要插件的东西,但我也会对那里的插件感兴趣。



这是我做了什么:

  selectValues = {1:test 1,2:test 2}; 

for(key in selectValues){
if(typeof(selectValues [key] =='string'){
$('#mySelect')。append('< ; option value ='+ key +'>'+ selectValues [key] +'< / option>');
}
}

干净/简单的解决方案:



这是一个清洁up and simplified matdumsa的版本

  $。each(selectValues,function(key,value) ){
$('#mySelect')
.append($('< option>',{value:key})
.text(value));
});

来自matdumsa的更改:(1)删除了append()中的选项的关闭标记(2)将属性/属性移动到地图中作为append()的第二个参数。

解决方案

S ame作为其他答案,以jQuery方式:

  $。each(selectValues,function(key,value){
$('#mySelect')
.append($(< option>< / option>)
.attr(value,key)
.text(value) );
});


What is the best method for adding options to a <select> from a JavaScript object using jQuery?

I'm looking for something that I don't need a plugin to do, but I would also be interested in the plugins that are out there.

This is what I did:

selectValues = { "1": "test 1", "2": "test 2" };

for (key in selectValues) {
  if (typeof (selectValues[key] == 'string') {
    $('#mySelect').append('<option value="' + key + '">' + selectValues[key] + '</option>');
  }
}

A clean/simple solution:

This is a cleaned up and simplified version of matdumsa's:

$.each(selectValues, function(key, value) {
     $('#mySelect')
          .append($('<option>', { value : key })
          .text(value));
});

Changes from matdumsa's: (1) removed the close tag for the option inside append() and (2) moved the properties/attributes into an map as the second parameter of append().

解决方案

Same as other answers, in jQuery fashion:

$.each(selectValues, function(key, value) {   
     $('#mySelect')
         .append($("<option></option>")
                    .attr("value",key)
                    .text(value)); 
});

这篇关于使用jQuery作为JS对象向select中添加选项的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆