首页 > 解决方案 > 相同的 javascript 变量和 html 元素名称位于不同的命名空间中并且不冲突?

问题描述

javascript 和 html 名称在不同的命名空间中并且不冲突?

我的意思是在 html 和 javascript 上下文中的“numberInputBox”下面的代码中是不同的,或者可能有问题?

<body>

<input name="numberInputBox" type="text" ></td>

<script type="text/javascript">
    var numberInputBox = document.getElementById("numberInputBox");
</script>

</body>

标签: javascripthtml

解决方案


给定一个带有idor的元素name浏览器将创建包含对它们的引用的全局 JS 变量

var numberInputBox = document.getElementById("numberInputBox");将覆盖该变量。这不会影响 HTML 元素

如果其他代码尝试使用全局变量并期望它具有其原始值(尽管在这种情况下,原始值与新值相同),它只会导致问题。

一般来说,最好避免创建全局变量,这样不同的脚本就不会相互影响

您可以使用 IIFE 来确定它们的范围。

(function () {
    var numberInputBox = document.getElementById("numberInputBox");
    // Do other stuff with numberInputBox here because it is local to this function
}());

推荐阅读