我需要优化这个Javascript实现,这样我就不会为每个需要调用Javascript的元素复制脚本。
下面的代码是我现在有的代码--我需要为每个类名为copy的元素调用Javascript。
<body>
<a id="copy-1" class="copy" data-clipboard-text="hello.playcraft.com" title="Click to copy me.">Copy 1 to Clipboard</a><br />
<a id="copy-2" class="copy" data-clipboard-text="localhost:25565" title="Click to copy me.">Copy 2 to Clipboard</a>
<script src="/assets/js/ZeroClipboard.min.js"></script>
<script>
var client = new ZeroClipboard( document.getElementById("copy-1") );
client.on( "ready", function( readyEvent ) {
// alert( "ZeroClipboard SWF is ready!" );
client.on( "aftercopy", function( event ) {
// `this` === `client`
// `event.target` === the element that was clicked
event.target.style.display = "none";
alert("Copied text to clipboard: " + event.data["text/plain"] );
});
});
</script>
</body>发布于 2015-04-11 13:58:12
你只需要一个函数。
function addCopyHandler(id) {
var client = new ZeroClipboard( document.getElementById(id) );
client.on( "ready", function( readyEvent ) {
// alert( "ZeroClipboard SWF is ready!" );
client.on( "aftercopy", function( event ) {
// `this` === `client`
// `event.target` === the element that was clicked
event.target.style.display = "none";
alert("Copied text to clipboard: " + event.data["text/plain"] );
});
});
}
addCopyHandler("copy-1");
addCopyHandler("copy-2");然后您可以添加一个循环
for(var i = 1; i <= 10; i++) {
addCopyHandler("copy-" + i);
}https://stackoverflow.com/questions/29578635
复制相似问题