我正在做一个带有选择的小网站项目,其中我将第一个不可选择的选项硬编码为占位符。关键是,之后当我动态添加选项时,它们似乎会覆盖硬编码的选项。
<!DOCTYPE html>
<html>
<head>
<title>Title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<h1>Title</h1>
<select id='select' name='select' required>
<option hidden disabled selected>Select placeholder</option>
</select><br>
<!-- More coding... -->
<script>
let a;
let aSelect = document.querySelector('#select');
fetch('./php/a.php', {
method: 'POST'
})
.then(res => res.json())
.then(data => {
a = data;
a.forEach(at => {
option = document.createElement('option');
let axy = at.x + ' ' + at.y;
option.value = at.id;
option.text = axy;
aSelect.appendChild(option);
});
});
</script>
</body>
</html>
上面的代码片段不会在选择中显示任何“选择占位符”选项。但我发现下面的内容,我也动态生成占位符选项。
<!DOCTYPE html>
<html>
<head>
<title>Title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<h1>Title</h1>
<select id='select' name='select' required>
</select><br>
<!-- More coding... -->
<script>
let a;
let aSelect = document.querySelector('#select');
fetch('./php/a.php', {
method: 'POST'
})
.then(res => res.json())
.then(data => {
a = data;
let option = document.createElement('option');
option.hidden = true;
option.disabled = true;
option.selected = true;
option.text = "Select placeholder";
aSelect.appendChild(option);
a.forEach(at => {
option = document.createElement('option');
let axy = at.x + ' ' + at.y;
option.value = at.id;
option.text = axy;
aSelect.appendChild(option);
});
});
</script>
</body>
</html>
这是为什么呢?我从文档中读到,
appendChild
不应替换元素,而应将它们附加在最后一个元素之后。我认为也许硬编码的选择选项不被视为“元素”,因此它们被动态生成的选项所取代......但这似乎不太可能,我在网上找不到任何东西。
P.S.:不要介意变量名称;它们不是不言自明的,因为它们是我的母语,但我不想翻译它们。
您的“选择占位符”选项处于隐藏状态,无法显示。根据浏览器及其版本,这会触发不同的行为。 即使您看到该选项本身,只要您单击它,该选项就会隐藏。看起来对此选择的动态访问也会触发此隐藏状态,这也会将其从您的视图中“删除”。
因此从选项中删除隐藏即可解决问题:
<!DOCTYPE html>
<html>
<head>
<title>Title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<h1>Title</h1>
<select id='select' name='select' required>
<option disabled selected>Select placeholder</option>
</select><br>
<!-- More coding... -->
<script>
const dummyData = [
{ id: 1, x: "Option 1", y: "Description 1" },
{ id: 2, x: "Option 2", y: "Description 2" },
{ id: 3, x: "Option 3", y: "Description 3" }
];
let a;
let aSelect = document.querySelector('#select');
Promise.resolve(dummyData)
.then(data => {
a = data;
a.forEach(at => {
option = document.createElement('option');
let axy = at.x + ' ' + at.y;
option.value = at.id;
option.text = axy;
aSelect.appendChild(option);
});
});
</script>
</body>
</html>