jQuery .clone() 仅获取 class 的第一个实例

jQuery .clone() only getting first instance of class

我在网络安装 WordPress 模板中有以下代码。我的目的是让非技术用户(帮助博客管理员保持内容新鲜的内容管理员等)通过博客查看角色 "custom-role" 的所有用户,然后单击按钮将所有电子邮件地址复制到文本区域这样她就可以将它们复制并粘贴到密件抄送字段中并与所有当前用户交流。

但是,脚本只是克隆 class "emails" 的第一个实例。我错过了什么?这不应该抓取 li.emails 的所有实例吗?

    <button id="copy">Copy all emails</button>
<textarea id="for-copy"></textarea>

    <?php

    $bcount = get_blog_count();

    global $wpdb;
    $blogs = $wpdb->get_results($wpdb->prepare("SELECT * FROM $wpdb->blogs WHERE 
    spam = '0' AND deleted = '0' and archived = '0' and public='1'"));
    if(!empty($blogs)){
        foreach($blogs as $blog){
            $details = get_blog_details($blog->blog_id);
            if($details != false){
                $addr = $details->siteurl;
                $name = $details->blogname;
                $id = $details->blog_id;
                $blogusers = get_users( 'blog_id='.$id.'&role=custom-role' );
                if (!empty($blogusers)) {
                    echo '<a href="'.$addr.'">'.$name.'</a>'.'<ul>';
                    foreach ( $blogusers as $user ) {
                    echo '<li class="emails">'.$user->user_email .'</li>';
                    }
                    echo '</ul>';
                }
            }
        }
    }
    ?>

<script>
(function($) {
$('#copy').click(function(e){
var new_list = $(".emails").clone();
$('#for-copy').append(new_list.html()); // also tried val()
});
})( jQuery );
</script>

来自jQuery docs on .html()

Get the HTML contents of the first element in the set of matched elements or set the HTML contents of every matched element.

这就是为什么您只获取第一个元素的原因。

如果您只想将字符串中的所有电子邮件地址粘贴到电子邮件客户端中,也许您可​​以这样做:

var emailAddresses = $('.emails').map(function(i, element) {
  return $(element).text();
}).toArray().join(';');

$('#for-copy').text(emailAddresses);

这将获取带有 .emails class 的所有元素,使用 .map() 遍历它们以获取文本,将结果转换为数组,然后将其转换为通过 .join() 的分号分隔字符串。在这种情况下,实际上不需要克隆元素。

我建议不要在这里使用 .clone(),而只是获取电子邮件地址。克隆方法确实最适合复制某些元素及其所有子元素以在页面上重新创建它。我建议只遍历 "emails" 元素:

var forcopy = $('#for-copy')
$('.emails').each(function() {
    forcopy.append($(this).text())
}