繁体   English   中英

JS document.getElementById() 与 Int

[英]JS document.getElementById() with Int

我通过document.getElementById({{templete_var}})获取一些DOM elements{{templete_var}}可以是Int 我想知道这是否会导致跨不同浏览器/设备的任何错误。 它在 Firefox (ubuntu) 和 Safari (Mac) 上运行良好,但是否有可能导致错误的移动浏览器?

这里有一个小代码片段来说明我的意思。 在代码片段中,这两种方法都有效。

 // 1 and 2 would be template variables here so I can't "hardcode" them document.getElementById(1).style.color = "blue" document.getElementById("2").style.color = "red"
 <span id="1">first text</span><br> <span id="2">other text</span>

令人惊讶的是,我找不到有关此主题的任何内容,如果这是重复的,请链接原件。

让我们看看,文档查询document.getElementById的语法只接受一个字符串值作为参数。 (请参阅document.getElementById )。 可能有几个用户代理(浏览器)是“智能的”并且在内部将整数 (1) 转换为 (“1”)。 但是你不能也不应该依赖它。 因此,解决方案是强制转换为字符串。

 const foo = 1; const bar = '2'; document.getElementById(''+ foo).style.color = "blue"; document.getElementById('' + bar).style.color = "red";
 <span id="1">first text</span><br> <span id="2">other text</span>

在这 2 个查询中,两个变量都将被强制为字符串, foo将转换为“1”,而bar将保持为“2”。

那么为什么不把它变成你得到的任何 id 的 .toString() 呢?

暂无
暂无

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

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