jQuery 向动态加载的选择添加选项
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5942613/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Adding options to a dynamically loaded select
提问by Lorenzo
Which is the best way to add <option>...</option>
to a select that has been dynamically added to the dom?
添加<option>...</option>
到已动态添加到 dom 的选择的最佳方法是什么?
I mean at a generic <select>
that has been added subsequently an ajax call. I would like to add the option before showing the select element.
我的意思是在<select>
随后添加了一个 ajax 调用的泛型。我想在显示选择元素之前添加该选项。
thanks!
谢谢!
EDIT
编辑
This is the function that I have
这是我的功能
$.ajax({
type: "get",
url: baseUrl + 'MyService.asmx/NewReferent',
data: JSON.stringify({}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
// Get the referent item from the webservice
var referent = msg.d;
// Render the template with the Referent data
var referentTemplate = $("#referentTemplate").tmpl(referent);
//add button style
$(".button", referentTemplate).button();
//Show the Dialog
$("#referent-dialog").empty().html(referentTemplate).dialog('open');
}
});
This is the code that I have to get the options from the server
这是我必须从服务器获取选项的代码
$.getJson(baseUrl + 'MyService.asmx/GetReferentTypes', function (data) {
$.each(data, function (key, value) {
$('#select_id').append($("<option></option>").attr("value", key).text(value));
});
});
EDIT 2
编辑 2
Unfortunately I am not able to understand what's going on with my code. With some little modification to the code of @Raynos I have been able to receive the following JSON data from the server
不幸的是,我无法理解我的代码发生了什么。通过对@Raynos 的代码稍加修改,我已经能够从服务器接收以下 JSON 数据
{"d":
[
{"__type":"Full.Namespace.Path.ReferentType","ReferentTypeID":1,"Description":"option1"},
{"__type":"Full.Namespace.Path.ReferentType","ReferentTypeID":2,"Description":"option2"}
]
}
that is not parsed correctly from my $.each()
function call. I have two question now:
从我的$.each()
函数调用中没有正确解析。我现在有两个问题:
- Who's going to add the _type parameter?
- How can I correct the parsing
each()
?
- 谁来添加 _type 参数?
- 我该如何纠正解析
each()
?
回答by Raynos
$("<select>").append(
$("<option>" , {
text: "foo",
value: "bar"
})
).appendTo("#container");
The trick is to append the options before you append the select to something.
诀窍是在将选择附加到某些内容之前附加选项。
Alternatively you can make sure to hide the select before you add it to the DOM.
或者,您可以确保在将选择添加到 DOM 之前隐藏它。
pseudo code:
伪代码:
$.when(ajax).then(function(html) {
var foo = $(html);
foo.find("select.SomeClass").hide();
...
});
...
$("select.SomeClass").append($("<option>")).show()
[[Edit]]
[[编辑]]
Use a simple bit of $.when
magic to make sure they happen in the write order. I.e. the select template is created then the options are appended
使用一些简单的$.when
魔法来确保它们按写入顺序发生。即创建选择模板然后附加选项
$.when(
$.ajax({
type: "get",
url: baseUrl + 'MyService.asmx/NewReferent',
data: JSON.stringify({}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
// Get the referent item from the webservice
var referent = msg.d;
// Render the template with the Referent data
var referentTemplate = $("#referentTemplate").tmpl(referent);
//add button style
$(".button", referentTemplate).button();
//Show the Dialog
$("#referent-dialog").empty().html(referentTemplate).dialog('open');
}
});
}).then(function() {
$.getJson(baseUrl + 'MyService.asmx/GetReferentTypes', function (data) {
$.each(data, function (key, value) {
$('#select_id').append($("<option></option>").attr("value", key).text(value));
});
});
});
[[Edit 2]]
[[编辑 2]]
Give your sample JSON structure
给出您的示例 JSON 结构
$.each(data.d, function (key, value) {
$('#select_id').append(
$("<option></option>")
.attr("value", value.ReferentTypeID)
.text(value.Description)
);
});
Would generate
会产生
<option value="0">option1</option>
<option value="1">option2</option>
回答by Srinivasan.S
This simple answer may be help you,
这个简单的答案可能对你有帮助,
var selectField = $('#' + id_of_field);
var empIds = [101, 102, 103];
var empNames = ['X', 'Y', 'Z'];
var options = '';
selectField.empty();
for ( var i = 0, len = empIds.length; i < len; i++) {
options += '<option value="' + empIds[i] + '">' + empNames[i] + '</option>';
}
selectField.append(options);