[英]removeChild doesn't work when called from a timeout at page load
I've got a HTML div that is supposed to hold dynamically generated children. 我有一个HTML div,它应该包含动态生成的子代。 Said children are to be removed from the list after a set amount of time (eg 1000 ms).
在设定的时间(例如1000 ms)后,将这些孩子从列表中删除。
I've seen people having issues about the scope in a timeout function but I don't think that's it. 我见过人们对超时功能的作用域有疑问,但我认为不是那样。
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 works every time. pushAlert每次都能工作。
popAlert works for times when pushAlert was called after page load. popAlert在页面加载后调用pushAlert的时间内起作用。
<script src='../js/alerts.js'></script>
<script>
pushAlert('info', 'info');
</script>
If I call pushAlert like this, the timeout that is supposed to call popAlert works, but popAlert does not remove the child. 如果我这样调用pushAlert,则应该调用popAlert的超时有效,但popAlert不会删除该子级。 But if I call pushAlert from the event of a form submit, everything works properly, including the timeout-ed popAlert.
但是,如果我从表单提交事件中调用pushAlert,则所有内容都可以正常工作,包括超时的popAlert。
EDIT: gif showing a visualization of the issue https://i.gyazo.com/aa3dc08af016450c7082482ec34a277c.mp4 编辑:显示问题可视化效果的gif https://i.gyazo.com/aa3dc08af016450c7082482ec34a277c.mp4
Use .firstElementChild
. 使用
.firstElementChild
。
.firstChild
will get first child which can be a node of any type . .firstChild
将获得第一个子节点,该子节点可以是任何类型的节点 。
.firstElementChild
will only get the first child which is a node of element type. .firstElementChild
将仅获取第一个子元素,该子元素是元素类型的节点。
To illustrate, you can click the two buttons in the snippet below to see the response: 为了说明这一点,您可以单击下面的代码片段中的两个按钮来查看响应:
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.