gpt4 book ai didi

javascript - 使用 document.getElementById 时,它无法正常工作

转载 作者:行者123 更新时间:2023-12-02 15:39:02 24 4
gpt4 key购买 nike

问题
我试图将函数的输出显示到 div,但我不明白为什么它不显示。我该如何解决这个问题才能正确显示?

到目前为止我尝试过的
我从我编写的另一个正在运行的代码块中复制了一个 document.getElementById 语句,并检查了它是否有任何拼写错误等。一切似乎都很好。我用谷歌搜索了innerHTML以确保我正确使用它。
还将 document.etc 行更改为 document.write 以确保该功能正常工作,正确输出。


我的代码

<html>
<head>
<script type="text/javascript">
function parameters(one, two) {
document.getElementById('output').innerHTML=(one + two);
}

parameters("coding" , "coffee");
</script>
</head>
<body>
<div id="output"></div>
</body>
</html>

最佳答案

问题是您正在尝试使用 div#output在浏览器加载之前。

对此有两个简单的解决方案:

第一

输入 <script> div#output 之后的标签,所以它已经被加载了。

<html>
<head>
</head>
<body>
<div id="output"></div>
<script type="text/javascript">
function parameters(one, two) {
document.getElementById('output').innerHTML=(one + two);
}

parameters("coding" , "coffee");
</script>
</body>
</html>

第二个

将您的 Javascript 代码放入 DOMContentLoaded 中事件,因此只有在页面中加载所有 DOMElement 后才会调用它。

<html>
<head>
<script type="text/javascript">
function parameters(one, two) {
document.getElementById('output').innerHTML=(one + two);
}

document.addEventListener('DOMContentLoaded', function() {
parameters("coding" , "coffee");
});
</script>
</head>
<body>
<div id="output"></div>
</body>
</html>

关于javascript - 使用 document.getElementById 时,它无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32722490/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com