简体   繁体   中英

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.

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

my js function to change class for div

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

in HTML I having five div as follows

<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() document. getElementById() rather than 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'; 

So, explicitly converting kx to a string 1 should remove that warning:

for (kx = 1; kx <= 5; kx++) {
    document.getElementById(kx).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. I've elected to use Number.prototype. toString() Number.prototype. toString() because, for the purspose of the example, the method call more clearly demonstrates the intent.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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