【问题标题】:Why doesn't jQuery Append work for the end of HTML List Items?为什么 jQuery Append 不适用于 HTML 列表项的末尾?
【发布时间】:2010-10-16 19:59:44
【问题描述】:

我正在尝试克隆一个列表项,然后将其附加到该克隆的列表项的底部,请注意它应该在被克隆的列表项下方,而不是在列表的底部,因为我可以这样做我。目的是将它与可排序的 jQuery.ui 一起使用。

一切正常,事实上我什至可以正确克隆和追加。但是,它在 before 结束 </li> 标记之后附加它,而对于我来说,我不能强迫它在 after 这个标记之后附加它。

这是 HTML 标记:

<ul id="column-2" class="connectedSortable">
    <li class="ui-state-default">
        <div class="label">feature</div>
        <div class="action">
            <div class="delete"></div>
            <div class="other"></div>
        </div>
    </li>
</ul>

我们关心的部分是class="other",点击它会复制列表项。

这是目前为止的 jQuery:

// This works fine
$(".other").click(function() {

    // This needs to be set (global) to be used later on in some future code.
    actionTarget = this;        

    // This grabs the whole list item
    var targetStory = $(actionTarget).parent().parent();

    // This clones the list item, as well as appending 
    // that clone to the cloned list item
    $(targetStory).clone().appendTo(targetStory);

})

这很好用,它抓取列表项,克隆它,然后将其转储到屏幕上 - 但在错误的位置:(

<ul id="column-2" class="connectedSortable">
    <li class="ui-state-default">
        <div class="label">feature</div>
        <div class="action">
            <div class="delete"></div>
            <div class="other"></div>
        </div>
        <li class="ui-state-default">
            <div class="label">feature</div>
            <div class="action">
                <div class="delete"></div>
                <div class="other"></div>
            </div>
        </li>
    </li>
</ul>

任何人都知道为什么它没有附加到被克隆的列表项的末尾,以及如何解决这个问题?

【问题讨论】:

    标签: jquery dom list append


    【解决方案1】:

    我认为insertAfter 是您正在寻找的。 after 将在克隆之后插入原始节点,而不是在原始节点之后插入克隆。像这样的东西应该可以工作:

    $(targetStory).clone().inserAfter(targetStory);
    

    【讨论】:

    • 感谢 Mishac,cobbal 已经找到了答案! $(targetStory).after(targetStory.clone());
    【解决方案2】:

    也许你想使用 after 而不是 appendTo

    【讨论】:

    • 是的!这可以解决问题,感谢 cobbal $(targetStory).after(targetStory.clone());
    • 供参考:docs.jquery.com/Manipulation/appendTo 声明您拥有的元素,它将在其中 - 只是放在其中内容的末尾。因此,附加这个词。 . 喜欢你之后发现是要走的路。
    • 没错,我错过了“里面”的澄清,太多的略读。
    【解决方案3】:

    我想你想要的是这样的:

    $(targetStory).clone().appendTo(targetStory.parent());
    

    【讨论】:

    • 几乎,这是我已经尝试过的东西。相反,它将它添加到列表的底部,而不是在列表项被克隆之后。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-18
    • 1970-01-01
    • 2022-01-21
    相关资源
    最近更新 更多