我已经看到了很多关于这个的问题,我想我已经浏览了几乎所有的问题,但还没有找到解决我的问题的方法。
正如我在标题中提到的,Firefox 返回这个异常 TypeError: document.getElementById(...) is null 而 Chrome 和 Safari 工作得很好。
// main.js:
import {
hideNavbar
} from './components/hide-navbar-onscroll.js';
import {
displayCookieNotice
} from './components/hide-cookie-notice.js';
import {
active
} from './components/active-menu.js';
import {
insertNews
} from './components/insert-news.js';
window.onscroll = hideNavbar;
displayCookieNotice();
active();
insertNews();
// components/hide-cookie-notice.js:
const displayCookieNotice = function(event) {
document.getElementById('cookie-notice').style.bottom = "0";
document.getElementById('cookie-button').addEventListener('click', function() {
document.getElementById('cookie-notice').style.bottom = "-64px";
})
}
export {
displayCookieNotice
};
<!-- index.html -->
<head>
<!--- ... --->
<script src="https://code.jquery.com/jquery-1.10.2.js">
</script>
</head>
<body>
<script>
<!--- ... --->
$.get("common/cookie-notice.html", function(data) {
$("#cookie-notice-placeholder").replaceWith(data);
});
</script>
<div>
<!--- ... --->
<div id="cookie-notice-placeholder">
</div>
</div>
<script type="module" src="js/main.js">
</script>
</body>
<!-- common/cookie-notice.html -->
<div id="cookie-notice">
<div class="cookie-text-box text-bright">
<div class="cookie-text">
<p class="margin-between">Diese Site verwendet Cookies</p>
<p class="margin-between"><a href="/datenschutz" target="blank" class="font-yant text-bright">Datenschutz</a></p>
</div>
<button class="btn btn-small" id="cookie-button">OK</button>
</div>
</div>
正如在其他类似问题中所指出的,这似乎与以下事实有关:在执行 document.getElementById 时,页面可能尚未完全加载并且未找到元素。出于这个原因,我之前已经将 script.js 移到了页面的末尾,但这没有任何效果。 我还尝试在加载 main.js 模块时添加“延迟”......也没有效果。
有人知道如何解决这个问题吗?