如何在 JAVASCRIPT 中通过变量传递参数

How to pass parameter by variable in JAVASCRIPT

我在高级模式下通过 closure-compiler 优化我的 JS 时收到警告消息并且未编译。

JSC_TYPE_MISMATCH: actual parameter 1 of Document.prototype.getElementById does not match formal parameter

我的 js 函数将 class 更改为 div

for (kx = 1; kx <= 5;kx=kx+1) {
document.getElementById(kx).className='newclass';
    }

在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>

此代码在正常情况下工作(没有压缩/优化),但在尝试优化它时显示 warning/error,我该如何修复它?

Closure 希望您将 string 传递给 文档。<a href="https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById" rel="nofollow noreferrer">getElementById()</a> 而不是 number.

JSC_TYPE_MISMATCH: actual parameter 1 of Document.prototype.getElementById does not match formal parameter
found : number
required: string
at line 3 character 24

document.getElementById(kx).className='newclass';

因此,将 kx 显式转换为 string1 应该会删除该警告:

for (kx = 1; kx <= 5; kx++) {
    document.getElementById(kx<b>.toString()</b>).className='newclass';
}

虽然我不知道我会打扰;原来的实际编译。您得到的是警告而不是错误(我怀疑),因为数字参数只会被强制转换为字符串。就是说,如果您的环境促进对错误的警告,无论如何...跳过箍。

1 值得注意的是,您可以通过简单地与空字符串连接将数字转换为字符串,即:''+kx,以及允许 type-coercion to do its thing. I've elected to use Number.prototype.<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toString" rel="nofollow noreferrer">toString()</a> 因为为了示例的目的,方法调用更清楚地展示了意图。