Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
335 views
in Technique[技术] by (71.8m points)

javascript - 用jQuery作为JS对象从选项中添加选项的最佳方法是什么?(What is the best way to add options to a select from as a JS object with jQuery?)

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

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

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 :

(这是matdumsa的简化版本 :)

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

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

  ask by Darryl Hein translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Same as other answers, in jQuery fashion:

(与其他答案相同,采用jQuery方式:)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...