Vanilla js如何在执行脚本之前检查html元素是否存在

Vanilla js how to check if html element exists before executing script

嘿,我想弄清楚如何让我的脚本在加载元素时等待执行它的一部分,但目前它主要只是传递它,而不是等待它。 在 vanilla js 中最好的方法是什么?

这是代码

this.heading = document.getElementById("heading");

我希望它等待或重复检查,直到标题每次都确定

谢谢

你可以反复检查标题,然后在得到标题后做一些事情。

var heading;

function getHeading() {
    var interval = setInterval(function() {
        if (heading = document.getElementById('heading')) {
            clearInterval(interval);
            console.log(heading);
            // do some stuff here with your heading
        }
    }, 100);  // 100 represents how often the script checks for existence of heading in ms
}

getHeading();

加载模板后执行此操作。反复检查是否发生了什么(轮询)通常不是一个好主意。这应该发生 因为 模板已加载。在你的情况下,它看起来像 goToRoute:

goToRoute: function (htmlName) {
    (function(scope) { 
        var url = 'views/' + htmlName,
            xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function () {
            if (this.readyState === 4 && this.status === 200) {
                scope.rootElem.innerHTML = this.responseText;

                // Now it's ready

            }
        };
        xhttp.open('GET', url, true);
        xhttp.send();
    })(this);
}

将您正在考虑的特定代码放入 goToRoute 可能没有意义;为了使其更加通用,您可以考虑让 goToRoute 接受回调参数,或使用事件。