Javascript 使用 jQuery 创建新元素的首选方式

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

The preferred way of creating a new element with jQuery

javascriptjqueryappendcreateelementjquery-append

提问by Ashwin

I've got 2 ways I can create a <div>using jQuery.

我有两种方法可以创建<div>using jQuery

Either:

任何一个:

var div = $("<div></div>");
$("#box").append(div);

Or:

或者:

$("#box").append("<div></div>");

What are the drawbacks of using second way other than re-usability?

除了可重用性之外,使用第二种方式有什么缺点?

回答by gdoron is supporting Monica

The first option gives you more flexibilty:

第一个选项为您提供了更大的灵活性:

var $div = $("<div>", {id: "foo", "class": "a"});
$div.click(function(){ /* ... */ });
$("#box").append($div);

And of course .html('*')overrides the content while .append('*')doesn't, but I guess, this wasn't your question.

当然.html('*')会覆盖内容而.append('*')不会覆盖,但我想,这不是你的问题。

Another good practice is prefixing your jQuery variables with $:
Is there any specific reason behind using $ with variable in jQuery

另一个好的做法是在你的 jQuery 变量前加上前缀$
在 jQuery 中使用 $ 和变量是否有任何特定的原因

Placing quotes around the "class"property name will make it more compatible with less flexible browsers.

"class"属性名称周围加上引号将使其与不太灵活的浏览器更兼容。

回答by Niranjan Singh

I personally think that it's more important for the code to be readable and editable than performant. Whichever one you find easier to look at and it should be the one you choose for above factors. You can write it as:

我个人认为代码的可读性和可编辑性比性​​能更重要。无论您发现哪个更容易查看,它都应该是您针对上述因素选择的那个。你可以把它写成:

$('#box').append(
  $('<div/>')
    .attr("id", "newDiv1")
    .addClass("newDiv purple bloated")
    .append("<span/>")
      .text("hello world")
);

And your first Method as:

你的第一个方法是:

// create an element with an object literal, defining properties
var $e = $("<div>", {id: "newDiv1", name: 'test', class: "aClass"});
$e.click(function(){ /* ... */ });
// add the element to the body
$("#box").append($e);

But as far as readability goes; the jQuery approach is my favorite. Follow this Helpful jQuery Tricks, Notes, and Best Practices

但就可读性而言;jQuery 方法是我最喜欢的。遵循这个有用的 jQuery 技巧、注释和最佳实践

回答by Darshan

Much more expressive way,

更有表现力的方式,

jQuery('<div/>', {
    "id": 'foo',
    "name": 'mainDiv',
    "class": 'wrapper',
    "click": function() {
      jQuery(this).toggleClass("test");
    }}).appendTo('selector');

Reference: Docs

参考:文档

回答by Alan Dong

According to the jQuery official documentation

根据jQuery官方文档

To create a HTML element, $("<div/>")or $("<div></div>")is preferred.

创建一个 HTML 元素,$("<div/>")或者$("<div></div>")是首选。

Then you can use either appendTo, append, before, afterand etc,. to insert the new element to the DOM.

然后,您可以使用appendToappendbeforeafter等。将新元素插入 DOM。

PS: jQuery Version 1.11.x

PS:jQuery 版本 1.11.x

回答by Anuradha Mudalige

According to the documentation for 3.4, It is preferred to use attributes with attr()method.

根据3.4的文档,最好将属性与attr()方法一起使用。

$('<div></div>').attr(
  {
    id: 'some dynanmic|static id',
    "class": 'some dynanmic|static class'
  }
).click(function() {
  $( "span", this ).addClass( "bar" ); // example from the docs
});

回答by jbabey

I would recommend the first option, where you actually build elements using jQuery. the second approach simply sets the innerHTML property of the element to a string, which happens to be HTML, and is more error prone and less flexible.

我会推荐第一个选项,您实际上使用 jQuery 构建元素。第二种方法只是将元素的innerHTML 属性设置为一个字符串,它恰好是HTML,并且更容易出错且不太灵活。

回答by Explosion Pills

If #boxis empty, nothing, but if it's not these do very different things. The former will add a divas the last child node of #box. The latter completely replaces the contents of #boxwith a single empty div, text and all.

如果#box是空的,什么都没有,但如果不是,这些做非常不同的事情。前者将添加 adiv作为 的最后一个子节点#box。后者#box用一个空的div、文本和全部完全替换了的内容。

回答by nabila_ahmed

It is also possible to create a div element in the following way:

也可以通过以下方式创建 div 元素:

var my_div = document.createElement('div');

add class

添加班级

my_div.classList.add('col-10');

also can perform append()and appendChild()

也可以执行append()appendChild()