简体   繁体   中英

Javascript .replace fails on specific server

I am having a problem with some Javascript which seems to work fine on my laptop when connected to localhost but not when the code is placed on a remote server and I connect to that from the same laptop and browser (IE11). The relevant code snippet is:

      var wktxt = inputs[i].getAttribute( "ondblClick" );
      wktxt = wktxt.replace("(" + rowno,  "(" + rowcnt)
      inputs[i].setAttribute( "ondblClick", wktxt );
      inputs[i].style.backgroundImage = "url()";  

It fails on the second line with "Object doesn't support property or method 'replace'" yet the problem is not hit locally and behaves precisely as intended (this is part of some logic that clones a row within an HTML table). When I initiate debugging on the failure, wktxt contains "function ondblclick() {AddNotes2(1,0) }", rowno is 1 and rowcnt is 7.

Any ideas? This code is executed within a loop - could it be anything to do with the var declaration being re-executed on each iteration?

Since the replace method is part of the string object prototype. It would seem that the result of your var wktxt may not always equal a string. To test this you can use the typof statement. Something like

if (typeof wktxt === 'string') {
    wktxt = wktxt.replace("(" + rowno,  "(" + rowcnt)
    inputs[i].setAttribute( "ondblClick", wktxt );
    inputs[i].style.backgroundImage = "url()";
}
else {
    //write some code here to put whatever you want in wktxt should it fail to evaluate to
    // a string
}

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