什么是从与jQuery阵列选项添加到一个选择的最佳方式? [英] What is the best way to add options to a select from an array with jQuery?

查看:110
本文介绍了什么是从与jQuery阵列选项添加到一个选择的最佳方式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是使用jQuery从JSON对象添加选项到选择最好的方法是什么?

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

我在找东西,我并不需要一个插件做的,但也会有兴趣是在那里的插件。

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

这是我做过什么:

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

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

一个干净/简单的解决方案:

这是一个清理和简化<一个href=\"http://stackoverflow.com/questions/170986/what-is-the-best-way-to-add-options-to-a-select-from-an-array-with-jquery/171007#171007\">version matdumsa的的:

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

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

这matdumsa的变化:(1)除去内追加(选项)的结束标记;(2)移动/属性的属性成图作为追加的第二个参数()

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().

推荐答案

像其他的答案,在jQuery的方式:

Same as other answers, in jQuery fashion:

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

这篇关于什么是从与jQuery阵列选项添加到一个选择的最佳方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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