在jquery中复制由换行符分隔的多个li文本

时间:2017-05-31 05:29:33

标签: javascript jquery html

我在li中有数据如图所示,当我点击复制时,它应该被复制到剪贴板

a[tab]b
c[tab]d
e[tab]f

javascript代码在这里

function copy(element) {
    var $temp = $("<input>");
    $("body").append($temp);
    $temp.val($(element).parent().text()).select();
    document.execCommand("copy");
    $temp.remove();
    $(element).parent().effect("highlight", {}, 1000);
}

<ul>
    <li>a<br/>b</li>
    <li>c<br/>c</li>
    <li>e<br/>f</li>
</ul>

1 个答案:

答案 0 :(得分:1)

尝试以下代码段

function copy(element) {
    // use textarea instead of input because newline character is skipped from it
    var $temp = $("<textarea/>");
    $("body").append($temp);
    // making a clone to prevent affecting original ul
    var clone = $(element).parent().clone();
    // now replacing br with tab
    $(clone).find('br').replaceWith("\t");
    $temp.val(
      // get all li text using map
      clone.map(function(){  
        return $(this).text()
      }).get().join("\n") // get and join by new line
      ).select();
    document.execCommand("copy");
    $temp.remove();
}

$('button').on('click',function(){
    copy($('ul').find('li'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
    <li>a<br/>b</li>
    <li>c<br/>c</li>
    <li>e<br/>f</li>
</ul>

<button>Copy</button>