简体   繁体   中英

Issue with Concatenating Strings in JavaScript

Hey I am trying to concatenate strings with javascript but I am having errors. Here is my code:

function popForm(){
   var v = document.getElementById('a1').innerHTML;

   document.getElementById("a1_i").innerHTML =
      "<input type='text' name='a1_i' value="+v+" />";
}

The element a1_i is a span that I am populating with the input tag shown above.

Further down I edit the element with ID a1:

document.getElementById("a1").innerHTML="blah bloop";

However when I try to view the result, all I can see is blah, not bloop.

Any suggestions?

If you take a look at the generated HTML, you can notice following:

<input type='text' name='a1_i' value=blah bloop />

As syntax highlighter suggests, value of the value attribute is blah , while bloop is another attribute. You just need to add quotes:

function popForm(){
  var v = document.getElementById('a1').innerHTML; 
  document.getElementById("a1_i").innerHTML="<input type='text' name='a1_i' value='" + v   + "' />";
}

But if v contains symbol ' , then you're in trouble again. So you either should replace them with HTML entities or follow jbabey's advice.

I concur with Jbabey, it will save you extra coding of text/html strings (error prone) in the future. JavaScript concatenation is pretty straight forward

*variable1 + "Text, note quotes around" + variablearray[1] + "etc...";*

Use the methods: document.createElement document.createTextNode appendChild

https://developer.mozilla.org/en-US/docs/DOM/document.createElement https://developer.mozilla.org/en-US/docs/DOM/Node.appendChild

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