2016-08-13 39 views
0

通过使用类似的ID我想复制到剪贴板方法,而无需onclick按钮。 只有id/class可以做到这一点吗?如果可能的话,任何人都可以给我这个方法的解决方案吗? 我几乎尝试了几种方法来做到这一点,但它不起作用。如何使用javascript或jquery将多个具有相同ID的预标签内容复制到剪贴板

<html> 
    <script src="jquery-1.8.3.min.js"></script> 
    <head> 
<style> 
    #tooltip{display: none;position: absolute;cursor: pointer;top:50px;border: solid 1px #eee;background-color:black;padding: 10px;z-index: 1000;color:white;} 
</style> 
</head> 
<span id="mytext">This is Example1</span> 
<span id="mytext">This is Example2</span> 
    <input id="copy_btn" type="button" value="copy"> 
<div id="tooltip">copied.</div> 
<script> 
    var copyBtn = document.querySelector('#copy_btn'); 
     copyBtn.addEventListener('click', function() { 
    var urlField = document.querySelector('#mytext'); 
    var range = document.createRange(); 
    range.selectNode(urlField); 
    window.getSelection().addRange(range); 
    document.execCommand('copy'); 
    }, false); 
    </script> 
<script> 
    $(document).ready(function() { 
    $("#copy_btn").click(function(evt) { 
     evt.preventDefault(); 
     $("#tooltip").show(); 
     $("#tooltip").hide(3000); 
     }); 
    }); 
</script> 

回答

0

你可以这样做。从id更改为mytext的类;

var myTextElements = $(".mytext"); 

var myTextContents = []; 
myTextElements.forEach(function(ele,ind){myTextContents.push($(ele).text();)});