javascript - 相同的 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>
解决方案
给定一个带有id
or的元素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
}());
推荐阅读
- spring - Spring - 当一个 Destination JndiObjectFactoryBean 被缓存时,它是否保持与 JMS 代理的任何连接?
- drools - Drools 编译器从 7.8.0.Final 开始显示规则已定义错误
- python-2.7 - 如何从另一个 Many2many 字段中获取字段值?
- python - 收到 OSError: [Errno 28] 设备上没有剩余空间后恢复 pickle 损坏的文件
- google-cloud-platform - Terraform:无法导入 Google VPC 网络
- linux-kernel - 当 dma_alloc_coherent 替换为 dma_map_single 时,DMA 写入失败
- jquery - 更改位置后,滚动到带有动画的元素
- c# - 从用户控件读取数据的问题
- node.js - 帖子的 Nuxt 问题
- javascript - 在 Vue.js 中,如何检测 created() 挂钩中的代码是否在浏览器中运行?