简体   繁体   English

jQuery向DOM添加元素:正确的方法

[英]jQuery adding element to the DOM: the right way

I'm wondering which approach is better and why: 我想知道哪种方法更好,为什么:

a) 一种)

  .append('<div class="load" id="XXX"></div>)

b) b)

  .append('<div></div>').addClass('load').attr('id', 'XXX')

c) C)

   your way

As of jQuery 1.4 you can pass a map object as a second parameter 从jQuery 1.4开始,您可以将地图对象作为第二个参数传递

$('<li/>', { 
  click:    function(){}, 
  id:       'test',
  addClass: 'clickable' 
});

I find this method much more readable than having a single string or many jQuery method calls and chaining. 我发现这个方法比单个字符串或许多jQuery方法调用和链接更具可读性。

Check the docs here . 这里查看文档。 Some issues with IE for input elements. IE输入元素的一些问题。

Anyway both when using jQuery or basic JavaScript, creating an element and its attributes in a string is discouraged. 无论如何,当使用jQuery或基本JavaScript时,不鼓励在字符串中创建元素及其属性。 Better to separate the creation and the attribution of the attributes. 最好将属性的创建和归属分开。

I created a fiddle for a direct comparison of the 3 jQuery methods, plus a pure JavaScript one. 我创建了一个小提琴,用于直接比较 3个jQuery方法,以及纯JavaScript方法。

While both the new 1.4 option and the usual one are pretty fast, the string method is slow as hell. 虽然新的1.4选项和通常的选项都非常快,但是字符串方法很慢。 This is no surprise since jQuery has to parse and interpret it all. 这并不奇怪,因为jQuery必须解析并解释它。

Of course, pure JS is always the fastest option ;) 当然,纯JS总是最快的选择;)

This is how I normally handle it using jQuery. 这就是我通常使用jQuery处理它的方式。 I find it more readable, but that is just preference. 我发现它更具可读性,但这只是偏好。

var newdiv = $('<div></div>');

newdiv
  .addClass('load')
  .attr('id', 'XXX');

$('#someElement').append(newdiv);

I like to create elements the old fashioned way 我喜欢用老式的方式创造元素

var aDiv = document.createElement("div");
aDiv.id="blah";
aDiv.className+="meh ";
document.body.appendChild(aDiv);

as to what's better though? 至于什么更好呢? no idea. 不知道。

新的答案,我经历并更新了某人的jsPerf测试,所以它实际上工作,似乎其他人是对的,我错了: http//jsperf.com/document-write-vs-document-createelement/4/

var div = $('<div class="load" id="test"></div>');
.append(div);

The first method is the "best" in that it is the fastest because it minimizes the underlying DOM operations. 第一种方法是“最好的”,因为它最快,因为它最小化了底层DOM操作。 Obviously as the element gets more complicated, constructing with jQuery methods gets more convenient and your definition of "best" might change. 显然,随着元素变得越来越复杂,使用jQuery方法构建变得更加方便,并且您对“最佳”的定义可能会发生变化。

Another option (even though it's a little more code to type but way cleaner in my opinion), is to use JAML . 另一种选择(即使它是一个多一点的代码类型,但在我看来, 这样清洁剂),是使用JAML Example: 例:

Jaml.register('new-div', function() {
  div({class:'load', id:'XXX'})
});

Once it's registered, it's super easy to render on the page: 一旦注册,就可以非常轻松地在页面上呈现:

$("#element-to-append-to").append( Jaml.render("new-div") );

Like I said, slightly more code to type, but once you have all these templates rendered it's incredibly easy to re-use the templates elsewhere. 就像我说的那样,要输入更多的代码,但是一旦你拥有了所有这些模板,就可以非常容易地在其他地方重复使用这些模板。

This has turned into more of an opinion question than an actual question that will have an answer, however I will give my opinion anyway. 这已成为一个意见问题,而不是一个能得到答案的实际问题,但无论如何我会发表意见。

I prefer to build the html as a string first, then pass it into jquery to turn it into html. 我更喜欢首先将html构建为字符串,然后将其传递给jquery以将其转换为html。 For example, 例如,

function buildDiv(obj){
  var str = [
    '<div id="',obj.id,'" class="',obj.class,'">',
      obj.content,
    '</div>'
  ].join("");
  return str;
}
$(buildDiv({
  id: "foo",
  class: "bar",
  content: "Test Content!"
}).appendTo(target);

I know that is overkill for creating a simple div, however it's very useful when you have to create a collection of something, such as turning an array into an ordered list. 我知道创建一个简单的div有点过分,但是当你必须创建一些东西时,例如将数组转换为有序列表,这非常有用。 This is basically the same thing as doing 这与做的基本相同

$("<div id='foo' class='bar'></div>");

only i used a function to generate the string. 只有我用一个函数来生成字符串。 This allows me to modify the function, then use the same function elsewhere to build other strings that need to follow the same template. 这允许我修改函数,然后在其他地方使用相同的函数来构建需要遵循相同模板的其他字符串。

What you consider "best" may vary from situation to situation based on the needs of the project. 根据项目的需要,您认为“最佳”的情况可能因情况而异。

I will however say it is much better(faster) to manipulate html before you append it. 但是我会说在你追加它之前操作html要好得多(更快)。

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

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