Javascript 使用 append() 附加大块 html

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10759426/
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-08-24 02:49:08  来源:igfitidea点击:

Appending large block of html with append()

javascriptjqueryhtmlappend

提问by Thomas

Im trying to append a large block of text using jquery's append().

我正在尝试使用 jquery 的 append() 附加一大块文本。

$('#add_contact_btn').click(function(event) {
    event.preventDefault();

    var large = '<div class="accordian_container"><a href="#" class="accordian_trigger"><h4>Co-Borrower Information</h4></a><hr/><div class="accordian_item" id="accord_item_2"><label> First Name</label><br/><input type="text"/><br/><label>Middle Name</label><br/>
            <input type="text"/><br/>
            <label>Last Name</label><br/>
            <input type="text" /><br/>
            <label>Home Number</label><br/>
            <input type="text"/><br>
            <label>Work Number</label><br/>
            <input type="text"/><br>
            <label>Cell Number</label><br/>
            <input type="text"/><br>
            </div>
            </div>';

    $('#accordion_container').append(large);



});

It doesn't seem to be working and after looking at the documentation for append(), I can't figure out why - any ideas? Is it the large amount of HTML that I am trying to append?

它似乎不起作用,在查看了 append() 的文档后,我不明白为什么 - 有什么想法吗?是我要附加的大量 HTML 吗?

回答by Jimbo Jonny

Modern Answer

现代答案

As ES6 (and beyond) becomes more common, and as more and more people transpile from ES6, we are more and more able to use template literals, which can be used as multiline strings:

随着 ES6(及更高版本)变得越来越普遍,以及越来越多的人从 ES6 转译,我们越来越能够使用模板文字,它可以用作多行字符串:

var myString = `<p>Line One</p>
<p>Line Two</p>
<p>Line Three</p>`;


Original 2012 Answer (ES5)

2012 年原始答案 (ES5)

Javascript does not have multiline strings in the way you are writing them, you can't just open a string on one line, go down a few lines and then close it. (there are some ways of doing multi-line strings in JS, but they are kind of backwards).

Javascript 没有您编写多行字符串的方式,您不能只在一行中打开一个字符串,向下几行然后关闭它。(在 JS 中有一些方法可以做多行字符串,但它们有点倒退)。

How most people do it is something like this:

大多数人的做法是这样的:

var myString = '<p>Line One</p>' +
'<p>Line Two</p>' +
'<p>Line Three</p>';

回答by rybo111

You should create a template in HTML that is hidden, then append its content HTML. For example:

您应该在 HTML 中创建一个隐藏的模板,然后附加其内容 HTML。例如:

<div class="hide" id="template">
  <b>Some HTML</b>
</div>

jQuery:

jQuery:

$("#container").append($("#template").html());

Putting HTML in a JavaScript string is harder to read and search for, is error prone and your IDE will struggle to format it properly.

将 HTML 放入 JavaScript 字符串更难阅读和搜索,容易出错,并且您的 IDE 将难以正确格式化它。



Update 2019

2019 年更新

Check out the templatetag, which was created for this purpose: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/template

查看template为此目的创建的标签:https: //developer.mozilla.org/en-US/docs/Web/HTML/Element/template

The templatetag is even allowed to contain what would be invalid HTML elsewhere, e.g. a tdtag outside a table.

template标签甚至允许包含什么是无效的HTML的其他地方,例如td标签之外table

回答by Kevin B

Remove the line breaks.

删除换行符。

http://jsfiddle.net/DmERt/

http://jsfiddle.net/DmERt/

var large = '<div class="accordian_container"><a href="#" class="accordian_trigger"><h4>Co-Borrower Information</h4></a><hr/><div class="accordian_item" id="accord_item_2"><label> First Name</label><br/><input type="text"/><br/><label>Middle Name</label><br/><input type="text"/><br/><label>Last Name</label><br/><input type="text" /><br/><label>Home Number</label><br/><input type="text"/><br><label>Work Number</label><br/><input type="text"/><br><label>Cell Number</label><br/><input type="text"/><br></div></div>';

$('#accordion_container').append(large);?

回答by David

It's my understanding that if you want to put your long string on multiple lines that it's more efficient to use an array of strings and join them.

我的理解是,如果您想将长字符串放在多行上,使用字符串数组并连接它们会更有效。

var bigString = [
    'some long text here',
    'more long text here',
    '...'
];
$('#accordion_container').append(bigString.join(''));

回答by Oliver Konig

You can use a backslash at the end of each line.

您可以在每行末尾使用反斜杠。

http://davidwalsh.name/multiline-javascript-strings

http://davidwalsh.name/multiline-javascript-strings

var multiStr = "This is the first line \
This is the second line \
This is more...";

回答by gustavwiz

Another alternative is Template literalswith back-ticks:

另一种选择是带有反引号的模板文字

var large = `some long text here
some long text here
some long text here`;

It's a fairly new syntax and not supported in IE though.

这是一种相当新的语法,但在 IE 中不受支持。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

回答by Ajay2707

Javascript have the option to extend multiple lines/HTML section into a single line, for each line of HTML row add backslash()to identify that its continue line.

Javascript 可以选择将多行/HTML 部分扩展为一行,为每一行 HTML 行添加反斜杠()以标识其继续行。

Note:-The only thing to consider while append lines are the single quote and double quote. If you start with the single quote, then use double quote in the internal string or vice-versa, otherwise, line is break and do not get the proper result.

注意:-附加行时唯一要考虑的是单引号和双引号。如果以单引号开头,则在内部字符串中使用双引号,反之亦然,否则,换行并不会得到正确的结果。

$(element).append('<div class="content"><div class="left"></div><div class="right"></div></div>');

Javascript syntax

Javascript 语法

 var str = ' <div class="content"> \
<div class="left"> \
</div> \
<div class="right"> \
</div> \
</div> ';

 document.getElementsByName(str).html(str);
 //or
 document.getElementsById(str).html(str);

Jquery syntax

jQuery 语法

 $(element).append(' \
  <div class="content"> \
    <div class="left"> \
    </div> \
    <div class="right"> \
    </div> \
  </div> \
');

Oryou can use a html template for this as mention in 3rd link via jquery

或者您可以为此使用 html 模板,如通过 jquery 在第三个链接中提到的

$("#div").load("/html_template.html");

http://www.no-margin-for-errors.com/blog/2010/06/17/javascript-tip-of-the-day-extending-a-string-across-multiple-lines/

http://www.no-margin-for-errors.com/blog/2010/06/17/javascript-tip-of-the-day-extending-a-string-across-multiple-lines/

Appending multiple html elements using Jquery

使用 Jquery 附加多个 html 元素

spread html in multiple lines javascript

在多行javascript中传播html

回答by alexoviedo999

You can also clone the div with jQuery and then append the clone--way less messy.

您还可以使用 jQuery 克隆 div,然后附加克隆 - 方式不那么混乱。

var accordionClone = $('.accordion_container').clone();
$('#accordion_container').append(accordionClone);

回答by Pete B

If line-breaks are an issue just use innerHTML, works in every browser since IE5:

如果换行是个问题,只需使用innerHTML,自IE5以来适用于所有浏览器:

$('#accordion_container')[0].innerHTML += large;?

Or, for collections:

或者,对于集合:

$('.accordion_container').forEach(function () {
    this.innerHTML += large;?
});

回答by Chidananda Nayak

just add like this $(#element).append(large_html),large_html in special character(``) and thank me later.

只需像这样large_html在特殊字符(``)中添加 $(#element).append( ),large_html 并稍后感谢我。