尝试使用 JS 删除 HTML 元素
2018-03-31
76
我正在尝试用 JS 创建图像旋转器。我在 CSS 中应用的淡入淡出动画仅适用于元素创建,因此我必须在循环的每次迭代中移除该元素。
我面临的问题在标题中 - 我似乎无法移除客户端图片,我也不知道为什么……有人能帮忙吗?
我收到的错误是: Uncaught TypeError:无法在“Node”上执行“removeChild”:参数 1 不是“Node”类型。
JS
function clientRotator(){
var section = document.getElementById("clients");
var clientImg = document.createElement("img");
clientImg.setAttribute("id", "rotator");
section.appendChild(clientImg);
clientImg.src = "assets/exxon-mobil.png";
var imgArray = ["assets/shell.png", "assets/bp.png", "assets/talisman.png", "assets/cnr-international.png", "assets/exxon-mobil.png"];
var delaySeconds = 3;
var iteration = 0;
setInterval(function(){
console.log(imgArray[iteration]);
section.removeChild(clientImg);
var clientImg = document.createElement("img");
clientImg.setAttribute("id", "rotator");
section.appendChild(clientImg);
clientImg.src = imgArray[iteration];
if (iteration < imgArray.length-1){
iteration += 1;
}
else {
iteration = 0;
}
}, delaySeconds * 1000)
}
window.addEventListener("load", clientRotator());
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="css/style.css">
<link href="https://use.fontawesome.com/releases/v5.0.6/css/all.css" rel="stylesheet">
</head>
<body>
<section id="header">
<img id="logo" src="assets/logo-new.png" alt="Logo">
</section>
<section id="clients">
<!-- Rotating images go here -->
</section>
<footer>
</footer>
</body>
<script src="scripts/main.js"></script>
</html>
2个回答
罪魁祸首是
var
关键字,它使其范围限制在函数内部。第二次迭代完全是一个新函数,其中
clientImg
甚至不存在。
function clientRotator() {
var section = document.getElementById("clients");
var clientImg = document.createElement("img");
clientImg.setAttribute("id", "rotator");
section.appendChild(clientImg);
clientImg.src = "assets/exxon-mobil.png";
var imgArray = ["assets/shell.png", "assets/bp.png", "assets/talisman.png", "assets/cnr-international.png", "assets/exxon-mobil.png"];
var delaySeconds = 3;
var iteration = 0;
setInterval(function() {
console.log(imgArray[iteration]);
if (!!clientImg);
section.removeChild(clientImg);
clientImg = document.createElement("img");
clientImg.setAttribute("id", "rotator");
section.appendChild(clientImg);
clientImg.src = imgArray[iteration];
if (iteration < imgArray.length - 1) {
iteration += 1;
} else {
iteration = 0;
}
}, delaySeconds * 1000)
}
window.addEventListener("load", clientRotator());
<link href="https://use.fontawesome.com/releases/v5.0.6/css/all.css" rel="stylesheet">
<section id="header">
<img id="logo" src="assets/logo-new.png" alt="Logo">
</section>
<section id="clients">
<!-- Rotating images go here -->
</section>
<footer>
</footer>
Praveen Kumar Purushothaman
2018-03-31
此行是错误的:
window.addEventListener("load", clientRotator());
它调用函数
clientRotator()
并将结果(可能未定义)添加为事件侦听器。换句话说,您的函数
clientRotator()
在文档完全加载之前被调用,因此您的 id 为
clients
的元素尚不存在。
您想要的是
window.addEventListener("load", clientRotator());
这会将函数本身添加为事件侦听器,因此仅在触发 load 事件时调用它。
Jan Misker
2018-03-31