javascript - 从页面加载超时调用 removeChild 不起作用
问题描述
我有一个 HTML div,它应该包含动态生成的子级。在设定的时间量(例如 1000 毫秒)之后,将要从列表中删除所述子项。
我见过有人对超时函数的范围有疑问,但我认为不是这样。
function pushAlert(type, text) {
let newItem;
// newItem gets generated here.
alertList.innerHTML += newItem;
setTimeout(() => {
popAlert();
}, 1000);
}
function popAlert(e) {
if (e) {
alertList.removeChild(e);
} else {
alertList.removeChild(alertList.firstChild); <!-- gets here but doesn't remove the child. console.log on alertList and alertList.firstChild displays the proper elements. -->
}
}
pushAlert 每次都有效。
popAlert 适用于页面加载后调用 pushAlert 的时间。
<script src='../js/alerts.js'></script>
<script>
pushAlert('info', 'info');
</script>
如果我像这样调用 pushAlert,则应该调用 popAlert 的超时有效,但 popAlert 不会删除孩子。但是,如果我从表单提交事件中调用 pushAlert,则一切正常,包括超时的 popAlert。
编辑: gif 显示问题的可视化https://i.gyazo.com/aa3dc08af016450c7082482ec34a277c.mp4
解决方案
.firstChild
将获得第一个子节点,它可以是任何类型的节点。
.firstElementChild
只会得到第一个子节点,它是元素类型的节点。
为了说明,您可以单击下面代码段中的两个按钮来查看响应:
firstChild.addEventListener('click', removeFirstChild);
firstElementChild.addEventListener('click', removeFirstElementChild);
function removeFirstChild(){
alertList.removeChild(alertList.firstChild);
}
function removeFirstElementChild(){
alertList.removeChild(alertList.firstElementChild);
}
<div id="alertList">
<p>This is paragraph 0.</p>
<p>This is paragraph 1.</p>
<p>This is paragraph 2.</p>
</div>
<button id="firstChild">firstChild</button>
<button id="firstElementChild">firstElementChild</button>