在 JavaScript/jQuery 中声明多行字符串 var

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21202782/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 20:21:37  来源:igfitidea点击:

Declare a string var with multiple lines in JavaScript/jQuery

javascriptjquery

提问by Chris

How do i declare a variable in jquery with multiple lines like,

我如何在 jquery 中用多行声明一个变量,例如,

original variable:

原始变量:

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

the variable i want to declare:

我要声明的变量:

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

回答by thefourtheye

You can use \to indicate that the line has not finished yet.

您可以使用\来表示该行尚未完成。

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

Note:When you use \, the whitespace in the following line will also be a part of the string, like this

注意:当你使用时\,下一行的空格也会成为字符串的一部分,像这样

console.log(h);

Output

输出

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

The best method is to use the one suggested by Mr.Alien in the comments section, concatenate the strings, like this

最好的方法是使用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);

Output

输出

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

回答by Mr. Alien

@thefourtheyeanswer is perfect, but if you want, you can also use concatenation here because sometimes \will be misleading, as you will think those are literal characters ..

@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);

Demo

演示