gpt4 book ai didi

javascript - 默认选择不显示在下拉列表中

转载 作者:行者123 更新时间:2023-11-30 11:36:11 25 4
gpt4 key购买 nike

这是从 php 文件动态加载的下拉框。我已经设置了一个默认选项 Select Language 但是一旦加载了 ajax 元素,它就不会显示。

即使在加载了 ajax 项目后,如何将选择的语言设置为默认语言?

<select id="name">
<option style="display:none;" selected>Select language</option>
</select>

<?php if (isset($_GET['place']) && $_GET['place'] != '') { ?>

<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script>
$.ajax({
type: "POST",
data: {place: '<?= $_GET["place"] ?>'},
url: 'listplace.php',
dataType: 'json',
success: function (json) {
if (json.option.length) {
var $el = $("#name");
$el.empty(); // remove old options
for (var i = 0; i < json.option.length; i++) {
$el.append($('<option>',
{
value: json.option[i],
text: json.option[i]
}));
}
}else {
alert('No data found!');
}
}
});
</script>

最佳答案

$el.empty() 语句从 select 中移除所有选项。您不应该删除第一个选项。

为此,使用not 方法和:first 伪类 以保持默认选项。

$el.find('option').not(':first').remove();

关于javascript - 默认选择不显示在下拉列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44325080/

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