针对多个元素优化Javascript

时间:2015-04-11 13:51:26

标签: javascript html

我需要优化此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>

1 个答案:

答案 0 :(得分:0)

你可以使用一个功能。

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);
}