0

I have the following code in a network install WordPress template. My intent is to allow a non-technical user (content manager who helps blog managers keep their content fresh, etc) to view all users of role "custom-role" by blog, then click the button to copy all email addresses to the textarea so she can copy and paste them into the bcc field and communicate with all current users.

However, the script is only cloning the first instance of class "emails". What am I missing? Shouldn't this grab all instances of 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>
4

2 回答 2

0

来自jQuery 文档.html()

获取匹配元素集中第一个元素的 HTML 内容或设置每个匹配元素的 HTML 内容。

所以这就是为什么你只得到第一个元素。

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

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

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

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

于 2018-11-05T20:45:38.037 回答
0

我建议不要在这里使用 .clone() ,而只是抓取电子邮件地址。clone 方法确实最适合复制某个元素及其所有子元素以在页面上重新创建它。我建议只迭代“电子邮件”元素:

var forcopy = $('#for-copy')
$('.emails').each(function() {
    forcopy.append($(this).text())
}
于 2018-11-05T20:52:09.513 回答