gpt4 book ai didi

javascript - 为什么我的选项标签没有附加到动态生成的选择标签上

转载 作者:行者123 更新时间:2023-11-28 17:00:53 24 4
gpt4 key购买 nike

我有一个动态生成的 select 标签,然后,我必须进行 ajax 调用来查询一些值并循环它并动态生成 options 标签。但由于某种原因,我无法将 option 标签附加到我的选择标签中。这不是异步问题吧?

const firstElemTd = $('#none td:first-child');

firstElemTd.append(`<select id="the-select"></select>`);

const selectTag = $(`#the-select`);

$.ajax({
method: 'GET',
url: url,
dataType: 'json',
success: function(response) {
$.each(response, function(key, balyu) {
selectTag.append($('<option>', {value: balyu.name}).text(balyu.name));
});
}
});

最佳答案

首先将 selectTag 创建为 jQuery 对象。然后您可以附加到它。

$(function(){
const $firstElemTd = $('#none td:first-child');
const $selectTag = $('<select></select>');
//append the selectTag to the td
$firstElemTd.append($selectTag);
//now that the selectTag is a distinct jQuery object you can append to it. EG:
var response = [{"name":"a"},{"name":"b"},{"name":"c"}];
$.each(response, function(key, balyu) {
$selectTag.append($('<option/>').val(balyu.name).text(balyu.name));
});

/* The same thing in the ajax response should work too.
(commented out here for the snippet)
$.ajax({
method: 'GET',
url: url,
dataType: 'json',
success: function(response) {
$.each(response, function(key, balyu) {
$selectTag.append($('<option/>').val(balyu.name).text(balyu.name));
});
}
});
*/
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="none"><tr><td></td></table>

关于javascript - 为什么我的选项标签没有附加到动态生成的选择标签上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57528539/

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