简体   繁体   English

JavaScript代码不会在代码运行时执行,但是当我调试它并在控制台中执行时,它可以工作

[英]JavaScript code is not executed during the runtime of the code, but when I debug it and execute in console, it works

I have a following code: 我有以下代码:

var e = document.getElementById("overlay");
e.parentNode.removeChild(e);

This code is supposed to remove the DOM element, but it doesn't. 该代码应删除DOM元素,但不能删除。 So I removed the code and added a breakpoint in its stead and input the code in the console during the pause manually, and it worked (ie the element was successfully removed). 因此,我删除了代码,并添加了一个断点,并在暂停期间手动在控制台中输入了代码,然后它起作用了(即,元素已成功删除)。

This behavior seems rather strange for me, so I wanted to ask, why does it happen and what can I do to inspect this peculiar issue? 这种行为对我来说似乎很奇怪,所以我想问一下,为什么会发生这种情况,我应该怎么做才能检查这个特殊的问题?

Thanks in advance. 提前致谢。

EDIT: Thanks for quick replies. 编辑:感谢您的快速答复。 Nonetheless, I want to make it perfectly clear that the element #overlay does exist at the time of the execution of the code. 尽管如此,我想非常清楚地表明, #overlay元素在代码执行时确实存在。 Moreover, when I put a debugging breakpoint at that place in the code and execute these two lines of code, it does have an effect on this particular existent element (which it doesn't without debugging). 而且,当我在代码中的那个位置放置调试断点并执行这两行代码时,它确实会对这个特定的现有元素产生影响(这不是没有调试的情况)。

EDIT 2: I was asked to clarify the code. 编辑2:我被要求澄清代码。 I execute the following code before the body (part of the queryloader2 plugin, which ensures image preloading): 我在bodyqueryloader2插件的一部分,可确保图像预加载)之前执行以下代码:

window.addEventListener('DOMContentLoaded', function() {
    new QueryLoader2(document.querySelector("body"), {});
});

No errors present (except for a 404 error because of missing image, which has no impact on Javascript). 不存在任何错误(由于缺少图像而导致的404错误除外,这对Javascript没有影响)。

As Teemu mentioned #overlay more than likely doesn't exist when the code is run. 正如Teemu提到的#overlay在运行代码时很可能不存在。

For a test.. Try wrapping your code in either of these... 为了进行测试..尝试将您的代码包装在以下任意一种中...

Javscript Javscript

window.onload = function () { /*your code*/ };

Jquery (if included) jQuery(如果包含)

$(document).ready(function () { /* your code*/ });

You should execute your code after the DOM tree has finished loading. 您应该在DOM树加载完成后执行代码。 One option is to wrap your code in a function that executes after the DOMContentLoaded event has been fired. 一种选择是将代码包装在触发DOMContentLoaded事件后执行的函数中。

document.addEventListener("DOMContentLoaded", function(event) { 
  // your code
});

Look at this answer for more information: $(document).ready equivalent without jQuery 查看此答案以获取更多信息: $(document).ready等效,不带jQuery

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM