简体   繁体   English

使用jQuery将HTML注入DOM的最佳方法是什么?

[英]What is the best way to inject HTML into the DOM with jQuery?

I'm working on a calendar page that allows a user to click on a day, and enter an entry for that day with a form that pops up. 我正在制作一个日历页面,允许用户点击一天,然后使用弹出的表单输入当天的条目。

I'm no stranger to DOM manipulation with jQuery, but this is something I've done before and I'm beginning to wonder if there's a more efficient way to do this? 我对jQuery的DOM操作并不陌生,但这是我以前做过的事情,我开始怀疑是否有更有效的方法来做到这一点?

Would building the HTML manually within JavaScript be the most efficient way performancewise (I assume this is true, over using functions like appendTo() etc) or would creating a hidden construct within the DOM and then cloning it be better? 在JavaScript中手动构建HTML是性能最有效的方式(我假设这是真的,比使用appendTo()等函数)或者在DOM中创建一个隐藏的构造然后克隆它会更好吗?

Ideally I want to know the optimal method of doing this to provide a balance between code neatness and performance. 理想情况下,我想知道这样做的最佳方法,以便在代码整洁性和性能之间取得平衡。

Thanks, 谢谢,

Will

Working with huge chunks of HTML strings in JavaScript can become very ugly very quickly. 在JavaScript中处理大量的HTML字符串会很快变得非常难看。 For this reason it might be worth considering a JavaScript "template engine". 因此,考虑使用JavaScript“模板引擎”可能是值得的。 They needn't be complicated - Check out this one by Resig. 它们不需要复杂 - 请用Resig查看这个

If you're not up for that then it's probably fine to just continue as you are. 如果你没有达到这个目标,那么你可能会继续保持原状。 Just remember that DOM manipulation is generally quite slow when compared to string manipulation. 请记住,与字符串操作相比,DOM操作通常非常慢。

An example of this performance gap: 这种性能差距的一个例子:

// DOM manipulation... slow
var items = ['list item 1', 'list item 2', 'list item 3'];
var UL = $('<ul/>');
$.each(items, function(){
    UL.append('<li>' + this + '</li>');
});

// String manipulation...fast
var items = ['list item 1', 'list item 2', 'list item 3'];
var UL = $('<ul/>').append( '<li>' + items.join('</li><li>') + '</li>' );

在这里你可以找到解释。

Maybe not the most popular approach. 也许不是最流行的方法。

Have the html code generated in the backend. 在后端生成html代码。 The dialog will be in a css hidden div. 该对话框将位于css隐藏的div中。 When you want it to "pop", just apply different css styles and change a hidden input value(i guess the dialog interacts with that certain date). 当你想要它“弹出”时,只需应用不同的CSS样式并更改隐藏的输入值(我猜对话框与该特定日期交互)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM