Javascript 使用 jQuery 创建嵌套 HTML 元素的最佳方法

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

Best way to create nested HTML elements with jQuery

javascriptjquerydomnested

提问by Maverick

If I need to create a couple of nested DOM elements, I know one way to do it, is to write them as long string and then place them in the document using a suitable jQuery function. Something like:

如果我需要创建几个嵌套的 DOM 元素,我知道一种方法是将它们写成长字符串,然后使用合适的 jQuery 函数将它们放在文档中。就像是:

elem.html(
'<div class="wrapper">
    <div class="inner">
        <span>Some text<span>
    </div>
    <div class="inner">
        <span>Other text<span>
    </div>
</div>'); 

This way is obviously not the cleanest. The sting doesn't take too long to get messy and editing becomes a problem. I much more prefer this notation:

这种方式显然不是最干净的。刺痛不需要太长时间就变得凌乱,编辑成为一个问题。我更喜欢这个符号:

$('<div></div>', {
    class : 'inner'
})
.appendTo( elem );

The problem is I don't know how to implement it efficiently when creating nested elements on the fly like above. So if there is way to do the 1st example with the 2nd notation, I'll be glad to learn about it.

问题是我不知道如何在像上面那样动态创建嵌套元素时有效地实现它。所以如果有办法用第二个符号来做第一个例子,我会很高兴了解它。

Basically, the question is, whats the best way to create nested HTML elements on the fly, without having to deal wit messy long strings?

基本上,问题是,动态创建嵌套 HTML 元素的最佳方法是什么,而不必处理凌乱的长字符串?

Note : I am aware of templating engines. However this is a question concerning the creation of just a couple of HTML elements on the fly. Like while building the DOM dependencies for a plugin or similar cases.

注意:我知道模板引擎。然而,这是一个关于动态创建几个 HTML 元素的问题。就像为插件或类似情况构建 DOM 依赖项一样。

回答by lucideer

write them as long string and than place them in the document using a suitable jQuery function. Something like:

将它们写成长字符串,然后使用合适的 jQuery 函数将它们放在文档中。就像是:

The problem with this approach is that you'll need a multi-line string - something Javascript doesn't support - so in reality you'll end up with:

这种方法的问题是你需要一个多行字符串——Javascript 不支持的东西——所以实际上你最终会得到:

elem.html(
'<div class="wrapper">'+
    '<div class="inner">'+
        '<span>Some text<span>'+
    '</div>'+
    '<div class="inner">'+
        '<span>Other text<span>'+
    '</div>'+
'</div>');

Using the method you suggested above, this is about as clean as I could manage to get it:

使用您上面建议的方法,这与我设法获得的方法一样干净:

elem.append(
    $('<div/>', {'class': 'wrapper'}).append(
        $('<div/>', {'class': 'inner'}).append(
            $('<span/>', {text: 'Some text'})
        )
    )
    .append(
        $('<div/>', {'class': 'inner'}).append(
            $('<span/>', {text: 'Other text'})
        )
    )
);

The other advantage to doing this is that you can (if desired) get direct references to each newly created element without having to re-query the DOM.

这样做的另一个好处是您可以(如果需要)直接引用每个新创建的元素,而无需重新查询 DOM。

I like to write polyglots, so to make my code re-usuable I usually do something like this, (as jQuery's .html()doesn't support XML):

我喜欢编写polyglots,所以为了使我的代码可重复使用,我通常会做这样的事情(因为 jQuery.html()不支持 XML):

// Define shorthand utility method
$.extend({
    el: function(el, props) {
        var $el = $(document.createElement(el));
        $el.attr(props);
        return $el;
    }
});

elem.append(
    $.el('div', {'class': 'wrapper'}).append(
        $.el('div', {'class': 'inner'}).append(
            $.el('span').text('Some text')
        )
    )
    .append(
        $.el('div', {'class': 'inner'}).append(
            $.el('span').text('Other text')
        )
    )
);

This isn't very different to method #2 but it gives you more portable code and doesn't rely internally on innerHTML.

这与方法#2 没有太大不同,但它为您提供了更多可移植的代码,并且在内部不依赖innerHTML.

回答by Brad Christie

I like the following approach myself:

我自己喜欢以下方法:

$('<div>',{
  'class' : 'wrapper',
  'html': $('<div>',{
    'class' : 'inner',
    'html' : $('<span>').text('Some text')
  }).add($('<div>',{
    'class' : 'inner',
    'html' : $('<span>').text('Other text')
  }))
}).appendTo('body');

Alternatively, create your wrapper first, and keep adding to it:

或者,先创建您的包装器,然后继续添加:

var $wrapper = $('<div>',{
    'class':'wrapper'
}).appendTo('body');
$('<div>',{
    'class':'inner',
    'html':$('<span>').text('Some text')
}).appendTo($wrapper);
$('<div>',{
    'class':'inner',
    'html':$('<span>').text('Other text')
}).appendTo($wrapper);

回答by Hugh Chapman

I found this solutionwhile I was researching something else. It's part of an "Introduction to jQuery"by the creator of jQuery and uses the end()function.

我在研究其他东西时找到了这个解决方案。它是jQuery创建者的“jQuery简介”的一部分,并使用了end()函数。

$("<li><a></a></li>") // li 
  .find("a") // a 
  .attr("href", "http://ejohn.org/") // a 
  .html("John Resig") // a 
  .end() // li 
  .appendTo("ul");

Applying to your question it would be ...

适用于您的问题,它将是...

$("<div><span></span></div>") // div 
  .addClass("inner") // div 
  .find("span") // span 
  .html("whatever you want here.") // span 
  .end() // div 
  .appendTo( elem ); 

回答by Hymanvsworld

There is a third way besides long ugly strings or huge methods chained together. You can use plain old variablesto hold the individualelements:

除了长而丑陋的字符串或链接在一起的巨大方法之外,还有第三种方式。您可以使用普通的旧变量来保存单个元素:

var $wrapper = $("<div/>", { class: "wrapper" }),
    $inner = $("<p/>", { class: "inner" }),
    $text = $("<span/>", { class: "text", text: "Some text" });

Then, tie it all together with append:

然后,将它们与append

$wrapper.append($inner.append($text)).appendTo("#whatever");

Result:

结果:

<div class="wrapper">
  <p class="inner">
    <span class="text">Some text</span>
  </p>
</div>

In my opinion this is by far the cleanest and most readable approach, and it also has the advantage of separating the data from the code.

在我看来,这是迄今为止最干净、最易读的方法,而且它还具有将数据与代码分离的优点。

EDIT:One caveat, however, is that there is no easy way to mix textContentwith nested elements (e.g., <p>Hello, <b>world!</b></p>.) In that case you would probably need to use one of the other techniques such as a string literal.

编辑:然而,一个警告是没有简单的方法来混合textContent嵌套元素(例如,<p>Hello, <b>world!</b></p>。)在这种情况下,您可能需要使用其他技术之一,例如字符串文字。

回答by matt3141

I like this approach

我喜欢这种方法

    $("<div>", {class: "wrapper"}).append(
        $("<div>", {class: "inner"}).append(
            $("<span>").text(
                "Some text"
            )
        ), 
        $("<div>", {class: "inner"}).append(
            $("<span>").text(
                "Some text"
            )
        )
    ).appendTo("body")

回答by x-yuri

Long string is obviously the cleanest way possible. You see the code properly nested without all those unnecessary extra noise like brackets, dollar signs and what not. Sure, it'd be advantages to be able to write it as a multiline string, but that's not possible for now. To me the point is to get rid of all the unneeded symbols. I don't know how comes the string gets messy and editing becomes a problem. If you've assigned a lot of classes you can put them on separate line:

长字符串显然是最干净的方式。您会看到代码正确嵌套,没有所有不必要的额外干扰,如括号、美元符号等等。当然,能够将它写为多行字符串是有好处的,但现在不可能。对我来说,重点是摆脱所有不需要的符号。我不知道字符串怎么会变得乱七八糟,编辑就成了一个问题。如果你分配了很多类,你可以把它们放在单独的行上:

'<div id="id-1"'
+ ' class="class-1 class-2 class-3 class-4 class-5 class-6">'
+ '</div>'

or this way:

或者这样:

'<div id="id-1" class="'
    + 'class-1 class-2 class-3 class-4 class-5 class-6'
+ '">'
+ '</div>'

Another option is probably to use hamlon the client side, if that's possible. That way you'll have even less unneeded noise.

haml如果可能,另一种选择可能是在客户端使用。这样你就可以减少不必要的噪音。