2015-07-04 49 views
0

所以我有一個網頁上的多個元素,我希望能夠被複制。 這些元素是用PHP輸出的,具體取決於API返回的內容。我一直在嘗試2天才能使這個工作,但我似乎無法看到我的代碼有什麼問題。Zeroclipboard與PHP和多個元素

這是取出

<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>"; 
    ?> 
+0

零剪貼板仍然是唯一或多或少可靠的方法來做到這一點。新的html5 clicpboard api仍然沒有足夠的可靠性來使用它。但請注意,零剪貼板需要將Flash安裝在客戶端瀏覽器中,而這種瀏覽器越來越少。此外,它使用的安全漏洞,可能會關閉一天... – arkascha

+0

所以閃光電影放置在按鈕上?您可以通過右鍵單擊按鈕進行檢查。你也應該檢查你的瀏覽器開發控制檯是否有任何javascript錯誤。 – arkascha

+0

哦,還有一件事我只是看到:你明顯不'htmlescape()'你在按鈕定義中注入的'$ element'值。這可能會破壞您的標記,具體取決於內容。 – arkascha

回答

0

所有不重要的事情你不能使用PHP,一起去的JavaScript這樣的代碼:

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

好吧,讓我能夠做出修正爲這個!這比我想象的要容易得多。我爲每個要複製的元素使用了一個類,但我仍然使用包含data-clipboard-text標籤的每個&的相同ID。所以最終的代碼看起來像這樣

//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>"; 
?>