克隆元素并将其添加到另一个元素中

Cloning element and adding it in another element

本文关键字:元素 另一个 添加      更新时间:2023-09-26

考虑以下HTML标记:

<form action="">
    <div class="row subtitle">
        <span>Some stuff.</span>
    </div>
    <div class="more_subtitles"></div>

<a href="#" class="white add_more"><span>Add more</span></a>
</form>

和jQuery:

$('.add_more').live('click', function() {
    var el_of_form, subtitle, more_subtitles;
    el_of_form = $(this).closest('form');
    subtitle       = $(el_of_form).find('.subtitle');
    more_subtitles = $(el_of_form).find('.more_subtitles');
    console.log(subtitle);
    console.log(more_subtitles);
    $(more_subtitles).add(subtitle);
    return false;
});

为什么它不起作用?console.log()找到这些元素。。。

我想实现的是,当按下按钮时,它会克隆subtitle元素并将其添加到more_subtitles元素中。用户可以一次又一次地重复。

more_subtitles.append(subtitle.clone());

Add不是您想要的方法。请尝试附加。

$(more_subtitles).append(subtitle.clone());

Add用于使用传递到Add中的选择器匹配的一组新元素来扩展当前匹配的元素。它不会影响DOM。

Append是将匹配的DOM元素添加到当前DOM元素的方法。