DOM elements
我document.getElementById({{templete_var}})
{{templete_var}}
// 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"
可以是Int。我想知道这是否会导致不同浏览器/设备之间的任何错误。它在Firefox(ubuntu)和Safari(Mac)上运行良好,但有可能是移动浏览器会导致错误吗?
这里有一个小代码片段,以明确我的意思。 在代码片段中,两种方法都有效...
<span id="1">first text</span><br>
<span id="2">other text</span>
&#13;
//range of preset functions styled as OP described
function a(){ console.log('a'); }
function b(){ console.log('b'); }
function c(){ console.log('c'); }
function d(){ console.log('d'); }
function e(){ console.log('e'); }
function f(){ console.log('f'); }
function g(){ console.log('g'); }
function h(){ console.log('h'); }
function i(){ console.log('i'); }
function j(){ console.log('j'); }
function k(){ console.log('k'); }
function l(){ console.log('l'); }
function m(){ console.log('m'); }
//This function will take the arguments, reduce their boolean value
//to a 1 or 0 using |0, concatenate the string of 1's and 0's,
//parse out the string from binary to decimal, and then
//access the array's index correlating to the given decimal.
var truthTable = function(){
var callers = [a,b,c,d,e,f,g,h,i,j,k,l,m];
var tar = [].reduce.call(arguments,(p,c) => p+(c|0),"");
callers[parseInt(tar,2)]();
};
truthTable (true,true,false);
truthTable (true,false,true);
truthTable (true,true);
truthTable (true,true,false,false);
&#13;
令人惊讶的是我找不到关于这个主题的任何内容,如果这是转发请链接原件。
答案 0 :(得分:0)
让我们看一下,文档查询document.getElementById
的语法只接受字符串值作为参数。 (见document.getElementById)。可能是一些用户代理(浏览器)是“智能”的,并在内部将整数(1)转换为(“1”)。但你不能和SHOULDNT依赖于此。因此,解决方案是强制转换为字符串。
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”。
答案 1 :(得分:-1)
为什么不把它变成.toString()你得到的任何id?