jQuery document.createElement等价?

本文翻译自:jQuery document.createElement equivalent?

I'm refactoring some old JavaScript code and there's a lot of DOM manipulation going on. 我正在重构一些旧的JavaScript代码,并且正在进行大量的DOM操作。

var d = document;
var odv = d.createElement("div");
odv.style.display = "none";
this.OuterDiv = odv;

var t = d.createElement("table");
t.cellSpacing = 0;
t.className = "text";
odv.appendChild(t);

I would like to know if there is a better way to do this using jQuery. 我想知道是否有更好的方法来使用jQuery。 I've been experimenting with: 我一直在尝试:

var odv = $.create("div");
$.append(odv);
// And many more

But I'm not sure if this is any better. 但我不确定这是否更好。


#1楼

参考:https://stackoom.com/question/17qU/jQuery-document-createElement等价


#2楼

I'm doing like that: 我这样做:

$('<div/>',{
    text: 'Div text',
    class: 'className'
}).appendTo('#parentDiv');

#3楼

since jQuery1.8 , using $.parseHTML() to create elements is a better choice. jQuery1.8 ,使用$.parseHTML()创建元素是一个更好的选择。

there are two benefits: 有两个好处:

1.if you use the old way, which may be something like $(string) , jQuery will examine the string to make sure you want to select a html tag or create a new element. 1.如果您使用旧的方式,可能类似于$(string) ,jQuery将检查字符串以确保您要选择html标记或创建新元素。 By using $.parseHTML() , you tell jQuery that you want to create a new element explicitly, so the performance may be a little better. 通过使用$.parseHTML() ,您告诉jQuery您要明确地创建一个新元素,因此性能可能会好一些。

2.much more important thing is that you may suffer from cross site attack ( more info ) if you use the old way. 2.更重要的是,如果你使用旧的方式,你可能会受到跨站点攻击( 更多信息 )。 if you have something like: 如果你有类似的东西:

    var userInput = window.prompt("please enter selector");
    $(userInput).hide();

a bad guy can input <script src="xss-attach.js"></script> to tease you. 坏人可以输入<script src="xss-attach.js"></script>来取笑你。 fortunately, $.parseHTML() avoid this embarrassment for you: 幸运的是, $.parseHTML()避免了这种尴尬:

var a = $('<div>')
// a is [<div>​</div>​]
var b = $.parseHTML('<div>')
// b is [<div>​</div>​]
$('<script src="xss-attach.js"></script>')
// jQuery returns [<script src=​"xss-attach.js">​</script>​]
$.parseHTML('<script src="xss-attach.js"></script>')
// jQuery returns []

However, please notice that a is a jQuery object while b is a html element: 但是,请注意a是jQuery对象,而b是html元素:

a.html('123')
// [<div>​123​</div>​]
b.html('123')
// TypeError: Object [object HTMLDivElement] has no method 'html'
$(b).html('123')
// [<div>​123​</div>​]

#4楼

UPDATE UPDATE

As of the latest versions of jQuery, the following method doesn't assign properties passed in the second Object 从jQuery的最新版本开始,以下方法不会分配在第二个Object中传递的属性

Previous answer 以前的答案

I feel using document.createElement('div') together with jQuery is faster: 我觉得使用document.createElement('div')jQuery更快:

$(document.createElement('div'), {
    text: 'Div text',
    'class': 'className'
}).appendTo('#parentDiv');

#5楼

I've just made a small jQuery plugin for that: https://github.com/ern0/jquery.create 我刚刚为它制作了一个小的jQuery插件: https//github.com/ern0/jquery.create

It follows your syntax: 它遵循您的语法:

var myDiv = $.create("div");

DOM node ID can be specified as second parameter: DOM节点ID可以指定为第二个参数:

var secondItem = $.create("div","item2");

Is it serious? 这是认真的吗? No. But this syntax is better than $("<div></div>") , and it's a very good value for that money. 不。但是这种语法比$(“<div> </ div>”)好 ,而且这个钱非常好。

I'm a new jQuery user, switching from DOMAssistant, which has a similar function: http://www.domassistant.com/documentation/DOMAssistantContent-module.php 我是一个新的jQuery用户,从DOMAssistant切换,它具有类似的功能: http//www.domassistant.com/documentation/DOMAssistantContent-module.php

My plugin is simpler, I think attrs and content is better to add by chaining methods: 我的插件更简单,我认为通过链接方法添加更好的内容和内容:

$("#container").append( $.create("div").addClass("box").html("Hello, world!") );

Also, it's a good example for a simple jQuery-plugin (the 100th one). 此外,它是一个简单的jQuery插件(第100个)的一个很好的例子。


#6楼

Though this is a very old question, I thought it would be nice to update it with recent information; 虽然这是一个非常古老的问题,但我认为用最新信息更新它会很好;

Since jQuery 1.8 there is a jQuery.parseHTML() function which is now a preferred way of creating elements. 从jQuery 1.8开始,有一个jQuery.parseHTML()函数,它现在是创建元素的首选方法。 Also, there are some issues with parsing HTML via $('(html code goes here)') , fo example official jQuery website mentions the following in one of their release notes : 此外,通过$('(html code goes here)')解析HTML存在一些问题,例如官方jQuery网站在其发布说明中提及以下内容:

Relaxed HTML parsing: You can once again have leading spaces or newlines before tags in $(htmlString). 轻松的HTML解析:您可以在$(htmlString)中的标签之前再次拥有前导空格或换行符。 We still strongly advise that you use $.parseHTML() when parsing HTML obtained from external sources, and may be making further changes to HTML parsing in the future. 我们仍强烈建议您在解析从外部源获取的HTML时使用$ .parseHTML(),并且可能在将来对HTML解析进行进一步更改。

To relate to the actual question, provided example could be translated to: 为了与实际问题相关,提供的示例可以转换为:

this.$OuterDiv = $($.parseHTML('<div></div>'))
    .hide()
    .append($($.parseHTML('<table></table>'))
        .attr({ cellSpacing : 0 })
        .addClass("text")
    )
;

which is unfortunately less convenient than using just $() , but it gives you more control, for example you may choose to exclude script tags (it will leave inline scripts like onclick though): 不幸的是,它比使用$()更方便,但它可以让你获得更多的控制权,例如你可以选择排除脚本标签(它会留下像onclick这样的内联脚本):

> $.parseHTML('<div onclick="a"></div><script></script>')
[<div onclick=​"a">​</div>​]

> $.parseHTML('<div onclick="a"></div><script></script>', document, true)
[<div onclick=​"a">​</div>​, <script>​</script>​]

Also, here's a benchmark from the top answer adjusted to the new reality: 此外,这里是从最佳答案调整到新现实的基准:

JSbin Link JSbin Link

jQuery 1.9.1 jQuery 1.9.1

$.parseHTML:    88ms
  $($.parseHTML): 240ms
  <div></div>:    138ms
  <div>:          143ms
  createElement:  64ms

It looks like parseHTML is much closer to createElement than $() , but all the boost is gone after wrapping the results in a new jQuery object 看起来parseHTML$()更接近createElement ,但是在将结果包装到新的jQuery对象之后,所有的提升都消失了

发布了0 篇原创文章 · 获赞 136 · 访问量 83万+

猜你喜欢

转载自blog.csdn.net/xfxf996/article/details/105262469