在setTimeout内部访问后,DOM元素神秘地消失

时间:2018-10-08 18:24:31

标签: javascript html

因此,我有一个功能pushSession,可以在给定的通讯端口上有效地建立串行连接。如果没有有效的连接,函数“ getCorrectDevice”将拒绝其承诺并跳转到.catch()。

这里是函数本身-

function pushSession(){
    grabValidDevices()
    .then(checkDeviceSupport)
    .then(getCorrectDevice)
    .then(insertSessionHTML)
    .then(connectPort)
    .catch(function(error){
        var flag = document.getElementById("error-flag")
        var errorContainer = document.getElementById("error-container")
        application.flags.push(error)
        flag.style.backgroundColor = "white"

        var count = 0
        //errorContainer.textContent = application.flags[count]
        count++

        setTimeout(function(errors){
            var flag = document.getElementById("error-flag")
            var errorContainer = document.getElementById("error-container")
            errorContainer.textContent = ""
            console.log("showing flag")
            flag.style.backgroundColor = "transparent"
            errors.flags = [] // once an error has been push to the UI, we can reset our flags
        }, 5000, application)    
    })
}

执行此代码后,最后在.catch()中检索到的元素“ flag”从我的DOM中消失了。-pof!-。

观察这种行为一段时间后,在我看来就像是更改元素样式的行为以某种方式导致将元素从DOM中删除。

在调用函数pushSession()之后(特别是在行:flag.style.backgroundColor = "white")之后,该元素消失了,不再可见。真正奇怪的是,元素背景实际上变成了白色,然后在setTimeout内部经过了五秒钟之后又再次变得透明。这会导致错误,告诉我变量标志未定义(因为DOM元素不再存在)。

我可以理解范围的问题,但这似乎与范围无关。就像我已经说过的那样,该元素在DOM中不再存在。

之前的.then()调用中没有传递任何内容,因此我也相信这与我的诺言或它们的返回值无关。

在我看来,我的承诺会在执行setTimeout回调之前返回,但是这对回调执行没有任何影响,我绝对看不到任何DOM的原因要删除的元素!

此行为是否有任何解释?

我在这里看到的唯一明显的解决方案是简单地通过append child动态地将元素重新添加回去,但这似乎很笨拙且不必要。

1 个答案:

答案 0 :(得分:3)

是的,就像评论中所说的那样,就像我猜的那样:由于error-flagerror-container的子代,因此您用error-container清除了errorContainer.textContent = "" ,该标志将从DOM中消失。 :)