我正在Codepen中练习一些JS,但我的代码似乎无法正常工作,我也不知道为什么。我已经尝试过谷歌搜索并在堆栈溢出中搜索问题数据库。这是我正在使用的所有代码
var newItemCounter = 1;
var unList = document.getElementById("list");
var button = document.getElementById("button");
var headline = document.getElementById("headline");
var listItems = document.getElementByID("list").getElementsByTagName("li");
list.addEventListener("click", activateItem);
function activateItem(e) {
if (e.target.nodeName == "LI") {
headline.innerHTML = e.target.innerHTML;
for (i = 0; i < e.target.parentNode.children.length; i++) {
e.target.parentNode.children[i].classList.remove("active");
}
e.target.classList.add("active");
}
}
button.addEventListener("click", createNewItem);
function createNewItem() {
list.innerHTML += "<li>Something new " + newItemCounter + "</li>";
newItemCounter++
}
.active{
background-color:blue;
}
<h1 id="headline">Click a list item to replace this text.</h1>
<button type="button" id="button">Add new item</button>
<ul id="list">
<li>First item</li>
<li>Second item</li>
<li>Third item</li>
<li>Fourth item</li>
<li>Fifth item</li>
</ul>
答案 0 :(得分:3)
更改var listItems = ...
document.getElementByID("list")
到
document.getElementById("list")
var newItemCounter = 1;
var unList = document.getElementById("list");
var button = document.getElementById("button");
var headline = document.getElementById("headline");
var listItems = document.getElementById("list").getElementsByTagName("li");
list.addEventListener("click", activateItem);
function activateItem(e) {
if (e.target.nodeName == "LI") {
headline.innerHTML = e.target.innerHTML;
for (i = 0; i < e.target.parentNode.children.length; i++) {
e.target.parentNode.children[i].classList.remove("active");
}
e.target.classList.add("active");
}
}
button.addEventListener("click", createNewItem);
function createNewItem() {
list.innerHTML += "<li>Something new " + newItemCounter + "</li>";
newItemCounter++
}
.active{
background-color:blue;
}
<h1 id="headline">Click a list item to replace this text.</h1>
<button type="button" id="button">Add new item</button>
<ul id="list">
<li>First item</li>
<li>Second item</li>
<li>Third item</li>
<li>Fourth item</li>
<li>Fifth item</li>
</ul>
答案 1 :(得分:-1)
将getElementByID更改为getElementById,它将起作用。 “ Id”不应使用大写字母