在 JavaScript/jQuery 中声明一个包含多行的字符串 var



如何在 jquery 中声明一个包含多行的变量,例如,

原始变量:

var h = '<label>Hello World, Welcome to the hotel</label><input type="button" value="Visit Hotel"><input type="button" value="Exit">';

我要声明的变量:

var h = '<label>Hello World, Welcome to the hotel</label>
              <input type="button" value="Visit Hotel">
              <input type="button" value="Exit">';
您可以使用

指示该行尚未完成。

var h= '<label>Hello World, Welcome to the hotel</label> 
              <input type="button" value="Visit Hotel"> 
              <input type="button" value="Exit">';

注意:当你使用时,下一行中的空格也将是字符串的一部分,像这样

console.log(h);

输出

<label>Hello World, Welcome to the hotel</label>               <input type="button" value="Visit Hotel">               <input type="button" value="Exit">

最好的方法是使用Mr.Alien在评论区建议的那个,连接字符串,像这样

var h = '<label>Hello World, Welcome to the hotel</label>' +
              '<input type="button" value="Visit Hotel">' +
              '<input type="button" value="Exit">';
console.log(h);

输出

<label>Hello World, Welcome to the hotel</label><input type="button" value="Visit Hotel"><input type="button" value="Exit">

Edit

现在您还可以使用 ES6 模板文字。

let str = `
  some
  random
  string
`;

您还可以轻松地插入上述字符串中的变量,而无需使用串联,例如:

let somestr = 'hello',
str = `
  ${somestr}
  world
`;
<小时 />

旧答案

@thefourtheye答案是完美的,但如果你愿意,你也可以在这里使用串联,因为有时会产生误导,因为你会认为这些是字面字符。

var h = '<label>Hello World, Welcome to the hotel</label>';
    h += '<input type="button" value="Visit Hotel"> '; 
    h += '<input type="button" value="Exit">';
console.log(h);

演示

在 ES6 中,您可以通过简单地将变量声明为:

const sampleString  = `Sample
                       text
                       here`;

这反过来评估为'Sample ntextnhere'您可以从这里阅读有关多行字符串的 ES6 规则的所有信息。

相关内容

最新更新