使用 jQuery 的 .html 方法时的多行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8676990/
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
Multiple lines when using jQuery's .html method
提问by timkl
I would like to have multiple lines when I use jQuery's html method, like this:
当我使用 jQuery 的 html 方法时,我想有多行,如下所示:
$("#someID").html("
<h1>Headline 1</h1>
<h1>Headline 2</h1>
");
However this snippet of code does not work. Is there a way to use multiple lines when using jQuery's html method?
但是,这段代码不起作用。使用jQuery的html方法时有没有办法使用多行?
回答by TheVillageIdiot
use \
to escape new line chars.
用于\
转义换行符。
$("#someID").html("\
<h1>Headline 1</h1>\
<h1>Headline 2</h1>\
");
View working example here: http://jsfiddle.net/amantur/yeDff/
在此处查看工作示例:http: //jsfiddle.net/amantur/yeDff/
回答by TheVillageIdiot
You could use string concatenation to join the new lines. Its clean too.
您可以使用字符串连接来连接新行。它也很干净。
$("#someID").html("" +
"<h1>Headline 1</h1>" +
"<h1>Headline 2</h1>");
回答by Izzy
It's a bit late but now can do even cleaner:
有点晚了,但现在可以做得更干净:
$("#someID").html(`
<h1>Headline 1</h1>
<h1>Headline 2</h1>
`);
And you can even add variables without concatenation:
您甚至可以在不串联的情况下添加变量:
$("#someID").html(`
<h1>${headline1}</h1>
<h1>${headline2}</h1>
`);