HTML 选项未追加



我正在尝试引导并使用一些javaScript构建HTML表单。为了简单起见,我试图简化我的问题(换句话说,我意识到这似乎是一种无用的形式(。

我基本上是尝试使用 javaScript 通过下拉选择(只是一个用于概念验证的选择选项(更新表单的第二项。我使用点击事件只是为了测试。如果我要在选择中硬编码,例如:<option>first selection</option>它按预期工作。

我可以看到单击事件正在注册,因为它确实更新了第一个参数,但它没有对下拉菜单执行任何操作。在W3schools上,它完成时选择框没有可见的更改,而StackOverflow上的截图会创建大量错误,表明它无法识别getElementID(这似乎很奇怪,因为它似乎确实识别出它以正确解决点击事件的第一行(。

无论如何。。。感谢帮助,我一定会接受。我确定我只是在做一些明显错误的事情,因为我在这方面还很陌生。

function afterButtonClicked() {
//this works and is just to confirm my listener is done correctly (I think)
var tEntry = document.getElementById("test_entry");
tEntry.value = "successfully clicked at " + new Date();
//this doesn't seem to do anything.
//I am expecting my drop down to now have the option "first selection"
var item = document.getElementbyId("my_selection");
var myOption1 = document.createElement("OPTION");
myOption.textContent = "first selection";
item.appendChild(myOption);
}
document.getElementById("aButton").addEventListener("click", afterButtonClicked);
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
</head>
<body>
<div class="container">
<div>
<div class="form-group">
<label for="test_entry">This box works okay</label>
<input type="text" class="form-control" id="test_entry">
</div>
<div class="form-group">
<label for="my_selection">I am trying to populate this drop down after a click</label>
<select class="form-control" id="my_selection">
</select>
</div>
<button class="btn btn-primary" id="aButton">Create Some Drop Down Options</button>
</div>
</div>
</body>
</html>

我相信这是一件容易的事情。我一定会接受任何指出我任性的人的答案。

你的 JS 中有两个错误

它的getElementByIdmyOption1应该myOption

function afterButtonClicked() {
//this works and is just to confirm my listener is done correctly (I think)
var tEntry = document.getElementById("test_entry");
tEntry.value = "successfully clicked at " + new Date();
//this doesn't seem to do anything.
//I am expecting my drop down to now have the option "first selection"
var item = document.getElementById("my_selection");
var myOption = document.createElement("OPTION");
myOption.textContent = "first selection";
item.appendChild(myOption);
}
document.getElementById("aButton").addEventListener("click", afterButtonClicked);

工作小提琴 : https://jsfiddle.net/wnxag1yz/

最新更新