与php和多个元素的Zeroclipboard

时间:2015-07-04 06:01:30

标签: php copy clipboard zeroclipboard

所以我在网页上有多个元素,我希望能够被复制。 元素是用PHP输出的,具体取决于API发回的内容。我已经尝试了2天才能使这个工作,但我似乎无法看到我的代码有什么问题。

这是代码中包含所有不重要的东西

<script src="js/vendor/modernizr-2.8.3.min.js"></script>
<script type="text/javascript" src="js/ZeroClipboard.js"></script>
<script src="js/sweetalert.min.js"></script>
<link rel="stylesheet" type="text/css" href="css/sweetalert.css">
<script type="text/javascript">

var clipboard = new ZeroClipboard(document.getElementById("copy"));

clipboard.on("ready", function(readyEvent) {
    clipboard.on("aftercopy", function(event) {
      sweetalert({
          title: "See you soon!",
          text: "Copied " + event.data["text/plain"],
          type: "success",
          showConfirmButton: false,
          timer: 2000
      });
    });
});
</script>

  <?php
    echo "<button class='btn btn-success' id='copy' data-clipboard-text='". $element ."'><i class='fa fa-copy'> </i> Copy</button>";
  ?>

2 个答案:

答案 0 :(得分:0)

你不能使用PHP,请使用这样的javascript:

function ClipBoard(id) {
    youobj = document.getElementById(id);
    holdtext.innerText = youobj.innerText;
    therange = holdtext.createTextRange();
    therange.execCommand("RemoveFormat"); 
    therange.execCommand("Copy");
}

答案 1 :(得分:0)

好吧,所以我能够解决这个问题!这比我想象的容易得多。我为每个要复制的元素使用了一个类,但我仍然使用相同的ID来表示每个元素。包括data-clipboard-text标签。所以最终的代码看起来像这样

//This Will load the lib
<script src="js/zeroclipboard.js"></script>
//This is the script. I should probably but it in its own .js file.
<script>
//Loading it with the document ready function meant that I wont have any
//Errors to do with the initialization of it.
  $(document).ready(function() {
//This makes a new var called clipboard and it will look for the class called "copyclass".
//If you try to find elements via ID it will not be able to because you can only
//use ID's with the same name once.
    var clipboard = new ZeroClipboard($('.copyclass'));

      clipboard.on("ready", function(readyEvent) {
        clipboard.on("aftercopy", function(event) {
//Simple JS alert.
          alert("Worked!");
        });
      });
    });
</script>

<?php
//The data which is sent to be used for the clipboard is then dyncamically assigned using
//PHP for the data-clipboard-text.
echo  "<td><button class='copyclass' id='copy' data-clipboard-text='". $element ."'><i class='fa fa-copy'> </i> Copy</button> </td>";
?>