gpt4 book ai didi

javascript - IE 中的 getElementById 问题?

转载 作者:行者123 更新时间:2023-12-04 02:12:36 30 4
gpt4 key购买 nike

为什么以下代码在 Firefox 和 Chrome 中运行良好,但在 IE6 和 IE8 中却出错?

<!DOCTYPE html>
<html>
<head></head>
<body>
<div id="abc"></div>
<script type="text/javascript">
var doLoad = function() {
// error in ie6 and ie8
abc = document.getElementById("abc");
abc.innerHTML = "hello world!";
// correct in ie6 and ie8
/*
var abc = document.getElementById("abc");
abc.innerHTML = "hello world!";
*/
// correct in ie6 and ie8
/*
xyz = document.getElementById("abc");
xyz.innerHTML = "hello world!";
*/
}
window.onload = doLoad;
</script>
</body>
</html>

但是如果我在 document.getElementById("abc"); 之前添加 var 或将 abc 重命名为 xyz, 它在 IE6 和 IE8 中运行良好。

最佳答案

IE 为每个具有 ID 的元素创建一个全局 JavaScript 变量。这些变量不能覆盖 afaik 并导致各种问题。

请牢记:不要创建与元素 ID 同名的全局变量。根本不要创建全局变量。

关于javascript - IE 中的 getElementById 问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10161631/

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