JS string concatenation in ie are error reporting solution

  • 2020-03-30 02:30:02
  • OfStack

Long time no js, a lot of things have forgotten. Recently, I encountered some problems when using js to concatenate strings. No matter how to concatenate strings, I reported an error in ie, which was very frustrating.

After a day, and picked up the code to look at the next, suddenly remembered in Java concatenation string escape characters, just remembered that js also has this thing.

Here it is:
tr += "<td><a href='javascript:void(0);' onclick='confirmDelOneInfo('"+url2+"','"+obj.title+"');'><img src='images/tab/010.gif'/>"; 

No error in the editor, no onclick in the browser, F12 error, look at the script, the string completely changed

tr += "<td><a href='javascript:void(0);' onclick='confirmDelOneInfo(""+url2+"",""+obj.title+"");'><img src='images/tab/010.gif'/> "  

That's fine.

Summary of knowledge:

Single and double quotes work the same way in js, but if you have single quotes in your string you should put double quotes outside, and if you have double quotes in your string you should put single quotes outside, so you don't have to escape characters.

The output above is:
onclick='confirmDelOneInfo("http://...?type=1&nodeId=11"," test 1");' 

See that in HTML, if you use single quotes on the outside, use double quotes on the inside, otherwise IE will report an error, so use the escape character \" to convert double quotes. When dynamically generating HTML elements, be especially careful about single and double quotation marks, as this can be a headache.

Ha ha, a little knowledge of the summary, welcome to correct...

Related articles: