0

如何将函数包装在不存在的 div 中?

到目前为止,我已经尝试过 .append 前后,但这会关闭标签。还尝试了.html,并在函数之后包装,没有运气。

$("#testing .input").each(function() {
    var s = $(this).find("li .value").text();
    // start wrap
    $("span.rune > span", this).each(function() {
        var e = $(this).text();
        $("#test-output").append('<span class="' +e+ ' Rune"></span>');
    });
    // stop wrap
    $("#test-output").append('<span>' +txtToNumber[s]+ '</span>');
});

开始 HTML :

<div id="test-output"></div>

结束 HTML:

<div id="test-output">
    <div class="three">
        <span class="Z Rune"></span>
        <span class="Y Rune"></span>
        <span class="X Rune"></span>
    </div>
</div>

谢谢!

4

1 回答 1

1

You can create elements in jQuery without appending them. Then they basically "don't exist yet", at least not in the DOM (they are disconnected). What you can also do is creating the .three element, append it to the DOM, and then append the .Rune elements to it:

// create .three element and append it to the DOM
var $three = $("<div>").addClass("three").appendTo("#test-output");

// map these elements to .Rune elements
$("span.rune > span", this).map(function() {
    var e = $(this).text();

    return $("<span>")
             .addClass(e)
             .addClass("Rune")
             .get(0);
}).appendTo($three);  // and append them to .three
于 2012-11-18T18:16:48.170 回答