I have a problem with compiling in Visual Studio with JavaScript. In line 11, where there is datos.innerHTML
,
alert("Hola Mundo");
var nombre = "Juan";
var altura = 180;
var concatenacion = nombre + " " + altura;
/*document.write(nombre);
document.write(altura);*/
/*document.write(concatenacion);*/
var datos = document.getElementById("datos");
datos.innerHTML = '
<h1>Soy la caja de datos</h1>
<h2>Mi nombres es: $(nombre)</h2>
<h3>Altura: $(altura)</h3>
';
there is a problem with the compilation. Does not accept labels h1, h2, h3
. Should I install an extension?
the other answer is correct, but you need to wrap with ${} for variable in order to used with ` (backticks)
datos.innerHTML = `
<h1>Soy la caja de datos</h1>
<h2>Mi nombres es: (${nombre})</h2>
<h3>Altura: (${altura})</h3>
`;
In Javascript, single/double quoted strings are always single line(without line continuations). To fix it, use a multiline string(aka template strings) by using backticks instead:
datos.innerHTML = `
<h1>Soy la caja de datos</h1>
<h2>Mi nombres es: $(nombre)</h2>
<h3>Altura: $(altura)</h3>
`;
Edit: see Ari Firmanto's answer about using ${}.
The single quotes in that statement need to be backticks/grave marks ` rather than ':
datos.innerHTML = `
<h1>Soy la caja de datos</h1>
<h2>Mi nombres es: $(nombre)</h2>
<h3>Altura: $(altura)</h3>
`;
Regular single and double quotes are for regular strings in JavaScript; template strings and multiline strings use the backtick character.
The error is because you have line breaks in the string.
Option 1
Keep the html string within quotes but concat the varialbles using +
operator
datos.innerHTML = '<h1>Soy la caja de datos</h1><h2>Mi nombres es: '
+ nombre +
'</h2><h3>Altura: '
+ altura + '</h3>';
Option 2
Use template literals and give variables like ${variable-name}
. Check the support for Internet explorer if you are using this method.
datos.innerHTML = `
<h1>Soy la caja de datos</h1>
<h2>Mi nombres es: ${nombre}</h2>
<h3>Altura: ${altura}</h3>
`;
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.