是jQuery的新手,想知道是否有人可以告诉我最佳实践......
我希望在页面中附加一个div元素,其中包含大量的html,并且不确定实现此目的的最佳方法是什么......或者如果使用jquery是明智的话......
例如,如果我想使用jquery将以下代码附加到页面,那么最好的方法是什么。
<div id="test">
<h1>This is the test</h1>
<p>Hello, just a test</p>
<a href="www.test.com">Click me</a>
<a href="www.test.com">Click me again</a>
</div>
答案 0 :(得分:21)
如果要按原样添加HTML,则只需使用jQuery追加功能。 例如:
$('body').append('
<div id="test">\
<h1>This is the test</h1>\
<p>Hello, just a test</p>\
<a href="www.test.com">Click me</a>\
<a href="www.test.com">Click me again</a>\
</div>');
根据您的要求将选择器从主体更改为其他DOM元素/选择器。
或者,如果您已在文档中使用ID为“test”的div元素,则可以使用html()函数设置内容,如下所示:
$("#test").html('<h1>This is the test</h1>\
<p>Hello, just a test</p>\
<a href="www.test.com">Click me</a>\
<a href="www.test.com">Click me again</a>');
答案 1 :(得分:4)
$("#id_of_div").append($("#id_of_div_that_you_wanna_append").html());
答案 2 :(得分:3)
$("#test").append("YOUR CONTENT GOES HERE");
答案 3 :(得分:0)
使用 ES6 (ECMAScript 2015),您现在可以使用反引号来包围所有HTML,即使是单引号或双引号(也可用于在中间添加变量)。
但是,由于问题似乎集中在添加整个块 一些现有元素之后,或许after
方法比append
方法更合适案件。这是它们之间的区别(运行代码段):
let $num = 0;
$('main').append(`
<article>
<h2>Appended ${++$num}</h2>
<p>Using 'single' and "double-quotes" without escaping!</p>
</article>
<article>
<h2>Appended ${++$num}</h2>
<p>Using 'single' and "double-quotes" without escaping!</p>
</article>
`).after(`
<footer>
<h2>Added after main</h2>
<p><b>${++$num} blocks</b> of multiple elements were added through jQuery</p>
</footer>
`);
&#13;
article {background: #eee;border:1px solid #000;padding:1rem}
main {background: #ccc;padding:1rem}
body {background: #aaa;padding:1rem}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<main>
<h1>Main section</h1>
<article>
<h2>jQuery</h2>
<p>Adding multiple elements...</p>
</article>
</main>
&#13;
如果您更喜欢这种替代语法,也可以使用等效的insertAfter
和appendTo
:$('<p>my html</p>').insertAfter('main')
包含要添加的HTML块的jQuery对象首先出现,您只需要在方法参数中引用该字符串。
答案 4 :(得分:0)
当前有以下方法:
使用“ +”连接HTML代码段。
使用“ \”转义。
使用“`”(反-,grave accent),不需要任何额外的操作。 ES2015 / ES6(Template literals)支持此方法。
添加一个隐藏的tag
,其中包含您需要的相同HTML代码,例如<p id="foo" style="display:none;">
,然后使用.append($('#foo').html());
。
现在将一些使用场景发布到上面提到的first three methods
(只需在Chrome
浏览器的控制台中运行它们):
我们可以清楚地看到它们之间的差异。