简体   繁体   English

无法访问DOM元素

[英]Can't access DOM element

I wrote a web application with a body onload event. 我编写了带有body onload事件的Web应用程序。 I know this isn't optimal so I want to use DOMContentLoaded to trigger my init event. 我知道这不是最佳选择,所以我想使用DOMContentLoaded触发我的init事件。

I have a strange problem, I can't access my DOM element and I don't know why :/. 我有一个奇怪的问题,我无法访问DOM元素,也不知道为什么:/。

HTML: HTML:

<!DOCTYPE html>
<html>
<head>
    <title>Test</title>
    <script type="text/javascript" src="main.js"></script>
</head>
<body>
    <div id="test">Hello World</div>
</body>
</html>

JS: JS:

// add event listener
document.addEventListener('DOMContentLoaded', init, false);

function init () {
    // pop up
    alert(document.getElementById(test).innerHTML);
}

Does somebody see the problem? 有人看到问题了吗?

You are passing the undefined variable test to the getElementById() function, instead of the string value 'test' . 您要将未定义的变量 test传递给getElementById()函数,而不是字符串'test'

So 所以

document.getElementById(test); // Incorrect - as an undefined varible

Should in fact be 实际上应该是

document.getElementById('test') // Correct - as a string value

Or 要么

var element_id = 'test';
document.getElementById(element_id) // Correct - as a defined variable

Add double quotes around test ie "test" 在测试周围添加双引号,即“ test”

document.addEventListener('DOMContentLoaded', init, false);

function init () {
    // pop up
    alert(document.getElementById("test").innerHTML);
}

If your init function is executed, then you might add quote arroud your id : 如果执行了init函数,则可以在id后面加上引号:

document.getElementById(test)

becomes 变成

document.getElementById('test')

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

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