0

我有一段由 jQuery 生成的 XML。

我想要的是

<booklists>
    <booklist>
        <userid>0</userid>
        <book>Foo</book>
        <book>Bar</book>
    </booklist>
    <booklist>
        <userid>1</userid>
        <book>Foo</book>
        <book>Bar</book>
    </booklist>
    <booklist>
        <userid>2</userid>
        <book>Foo</book>
        <book>Bar</book>
    </booklist>
    <booklist>
        <userid>3</userid>
        <book>Foo</book>
        <book>Bar</book>
    </booklist>
    <booklist>
        <userid>4</userid>
        <book>Foo</book>
        <book>Bar</book>
    </booklist>
</booklists>

我得到了什么

<booklists>
    <booklist>
        <userid>0</userid>
        <book>Foo</book>
        <book>Bar</book>
    </booklist>
    <booklist>
        <userid>4</userid>
        <userid>3</userid>
        <userid>2</userid>
        <userid>1</userid>
        <book>Foo</book>
        <book>Bar</book>
    </booklist>
</booklists>

我的代码

lists = $('<booklists />')
books = $('<booklist />');

book = $('<book>Foo</book>');
books.append(book);

book = $('<book>Bar</book>');
books.append(book);

temp = books.clone();

for (var i = 0; i < 5; i++) {
    books.prepend('<userid>' + i + '</userid>');
    lists.append(books);
    books = temp;
}

$('.output').html(lists);

例子

http://jsfiddle.net/q6Q4A/

4

2 回答 2

3
books = temp;

需要是

books = temp.clone();
于 2013-04-16T11:21:32.190 回答
2

似乎您想将.clone()呼叫移入循环:

var lists = $('<booklists />'),
    books = $('<booklist />');
books.append('<book>Foo</book>').append('<book>Bar</book>');

for (var i = 0; i < 5; i++) {
    var temp = books.clone();
    temp.prepend('<userid>' + i + '</userid>');
    lists.append(temp);
}

$('.output').html(lists);

顺便说一句,我认为您不应该尝试在 HTML 文档中创建 XML 节点 - 它可能不适用于每个浏览器。

于 2013-04-16T11:22:14.067 回答