[英]How to pass parameter by variable in JAVASCRIPT
I am getting warning message and not compiled while optimizing my JS through closure-compiler in advanced mode. 我在高级模式下通过闭包编译器优化我的JS时收到警告消息,但未编译。
JSC_TYPE_MISMATCH: actual parameter 1 of Document.prototype.getElementById does not match formal parameter
JSC_TYPE_MISMATCH:Document.prototype.getElementById的实际参数1与形式参数不匹配
my js function to change class for div 我的js函数更改div的类
for (kx = 1; kx <= 5;kx=kx+1) {
document.getElementById(kx).className='newclass';
}
in HTML I having five div as follows 在HTML中我有五个div如下
<div id='1' class ='first'> contents </div>
<div id='2' class ='first'> contents </div>
<div id='3' class ='first'> contents </div>
<div id='4' class ='first'> contents </div>
<div id='5' class ='first'> contents </div>
this code working in normal case (without compress / optimization), but while trying to optimize it showing warning/error, How can I fix it? 此代码在正常情况下(无需压缩/优化)可以正常工作,但是在尝试对其进行优化时却显示警告/错误,如何解决?
Closure expects you to pass a string
to document. getElementById()
Closure希望您将
string
传递给document. getElementById()
document. getElementById()
rather than a number
. document. getElementById()
而不是number
。
JSC_TYPE_MISMATCH: actual parameter 1 of Document.prototype.getElementById does not match formal parameter
JSC_TYPE_MISMATCH:Document.prototype.getElementById的实际参数1与形式参数不匹配
found : number找到:号码
required: string必需:字符串
at line 3 character 24在第3行字符24
document.getElementById(kx).className='newclass';
So, explicitly converting kx
to a string
1 should remove that warning: 因此,将
kx
显式转换为string
1应该删除该警告:
for (kx = 1; kx <= 5; kx++) {
document.getElementById(kx
.toString()).className='newclass';
}
I don't know that I'd bother, though; 不过,我不知道我会打扰。 the original actually compiles.
原始文件实际上可以编译。 You got a warning rather than an error (I suspect) because a numeric argument will simply be coerced into a string.
您得到警告而非错误(我怀疑),因为数字参数将被简单地强制转换为字符串。 That said, if your environment promotes warnings to errors, by all means... jump through the hoops.
就是说,如果您的环境向错误提示警告,则一定要跳过去。
1 It's worth noting that you can convert a number to a string by simply concatenating with an empty string, ie: ''+kx
, and allowing type-coercion to do its thing. 1值得注意的是,您可以通过简单地将一个空字符串(例如:
''+kx
)连接起来并允许类型强制执行其操作来将数字转换为字符串。 I've elected to use Number.prototype. toString()
我选择使用
Number.prototype. toString()
Number.prototype. toString()
because, for the purspose of the example, the method call more clearly demonstrates the intent. Number.prototype. toString()
因为出于示例的目的,方法调用更清楚地说明了意图。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.