简体   繁体   English

Visual Studio Code With JS 报错,如何解决?

[英]Error in Visual Studio Code With JS, how to solve?

I have a problem with compiling in Visual Studio with JavaScript.我在使用 JavaScript 在 Visual Studio 中编译时遇到问题。 In line 11, where there is datos.innerHTML ,在第 11 行,有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 .不接受标签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).在 Javascript 中,单引号/双引号字符串总是单行(没有续行)。 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 ${}.编辑:请参阅 Ari Firmanto 关于使用 ${} 的回答。

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;常规单引号和双引号用于 JavaScript 中的常规字符串; template strings and multiline strings use the backtick character.模板字符串和多行字符串使用反引号字符。

The error is because you have line breaks in the string.该错误是因为您在字符串中有换行符。

Option 1选项1

Keep the html string within quotes but concat the varialbles using + operator将 html 字符串保留在引号内,但使用+运算符连接变量

datos.innerHTML = '<h1>Soy la caja de datos</h1><h2>Mi nombres es: ' 
                   + nombre + 
                   '</h2><h3>Altura: ' 
                   + altura + '</h3>';

Option 2选项 2

Use template literals and give variables like ${variable-name} .使用模板文字并给出${variable-name}类的变量。 Check the support for Internet explorer if you are using this method.如果您使用此方法,请检查对 Internet Explorer 的支持。

datos.innerHTML = `
    <h1>Soy la caja de datos</h1>
    <h2>Mi nombres es: ${nombre}</h2>
    <h3>Altura: ${altura}</h3>
`;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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