gpt4 book ai didi

jquery - 将选项添加到动态加载的选择中

转载 作者:行者123 更新时间:2023-12-01 02:04:08 24 4
gpt4 key购买 nike

这是添加 <option>...</option> 的最佳方式到已动态添加到 dom 的选择?

我的意思是通用的 <select>随后添加了 ajax 调用。我想在显示选择元素之前添加该选项。

谢谢!

编辑

这是我的功能

$.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');
}
});

这是我必须从服务器获取选项的代码

$.getJson(baseUrl + 'MyService.asmx/GetReferentTypes', function (data) {
$.each(data, function (key, value) {
$('#select_id').append($("<option></option>").attr("value", key).text(value));
});
});

编辑2

不幸的是,我无法理解我的代码发生了什么。通过对 @Raynos 的代码进行一些小的修改,我已经能够从服务器接收以下 JSON 数据

{"d":
[
{"__type":"Full.Namespace.Path.ReferentType","ReferentTypeID":1,"Description":"option1"},
{"__type":"Full.Namespace.Path.ReferentType","ReferentTypeID":2,"Description":"option2"}
]
}

未从我的 $.each() 正确解析函数调用。我现在有两个问题:

  • 谁将添加 _type 参数?
  • 如何更正解析 each()

最佳答案

$("<select>").append(
$("<option>" , {
text: "foo",
value: "bar"
})
).appendTo("#container");

诀窍是在将选择附加到某些内容之前附加选项。

或者,您可以确保在将选择添加到 DOM 之前隐藏该选择。

伪代码:

$.when(ajax).then(function(html) {
var foo = $(html);
foo.find("select.SomeClass").hide();
...
});

...

$("select.SomeClass").append($("<option>")).show()

[[编辑]]

使用一点简单的 $.when 魔法来确保它们按写入顺序发生。 IE。创建选择模板,然后附加选项

$.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));
});
});
});

[[编辑2]]

给出您的示例 JSON 结构

$.each(data.d, function (key, value) {
$('#select_id').append(
$("<option></option>")
.attr("value", value.ReferentTypeID)
.text(value.Description)
);
});

会生成

<option value="0">option1</option>
<option value="1">option2</option>

关于jquery - 将选项添加到动态加载的选择中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5942613/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com