如何使用带有动态内容和触发器的剪贴板.js进行复制

How to copy using clipboard.js with dynamic content and triggers

本文关键字:剪贴板 js 复制 触发器 何使用 动态      更新时间:2023-09-26

点击.fw-code-copy-button后,我想从最近的容器中复制源代码。.fw-code-copy-button-s是动态创建的,在用户点击专用的"查看源代码"按钮后。

Html,例如按钮:

<span class="fw-code-copy">
  <span class="fw-code-copy-button" data-clipboard-text="...">copy</span>
</span>

这就是我触发点击事件的方式,并定义要复制到剪贴板的源代码:

$(document).on("click", ".fw-code-copy-button", function(){
  var source = $(this).closest(".fw-code-copy").next("code").text();
});

这就是clipboard.js如何触发它的复制事件

new Clipboard(".fw-code-copy-button", {
  text: function(trigger) {
    return source; // source should somehow be copied from scope above it
  }
});

每当我点击网站上的任何地方,都会出现以下错误:

Uncaught Error: Missing required attributes, use either "target" or "text"

但首先我不想定义要在data-clipboard-text="..."中复制的文本然后以CCD_ 5作为其值来定义CCD_。

如果有人愿意支付一秒钟,我将非常感激。

[edit]我已经编写了jsFiddle进行演示,令人惊讶的是UncaughtError消失了,但我仍然需要将source代码从onClick范围移动到剪贴板范围。

https://jsfiddle.net/2rjbtg0c/1/

根据您的原始代码:

 new Clipboard(".fw-code-copy-button", {
  text: function(trigger) {
    return $(trigger).closest(".fw-code-copy").next("code").text(); 
  }
});

触发器是您单击的按钮。获取父级,然后返回代码块内的文本。您还需要修剪任何前导和尾随空白。

Demo

这将抓取代码块中的文本,如您所包含的示例中所示

new Clipboard(".fw-code-copy-button", {
  text: function(trigger) {
    return $(trigger).parent().find('code').first().text().trim();
  }
});
.fw-code-copy {
  display: block;
  position: relative;
  width: 400px;
  height: 30px;
  background: #FFE;
  border: thin solid #FF0;
  margin-bottom: 0.5em;
  padding: 0.5em;
}
.fw-code-copy-button {
  position: absolute;
  top: 8px;
  right: 8px;
  padding: 0.25em;
  border: thin solid #777;
  background: #800080;
  color: #FFF;
}
.fw-code-copy-button:hover {
  border: thin solid #DDD;
  background: #992699;
  cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/1.5.3/clipboard.min.js"></script>
<span class="fw-code-copy">
  <span class="fw-code-copy-button">Copy</span>
  <code>&lt;link rel=&quot;stylesheet&quot; href=&quot;style-1.css&quot;&gt;</code>
</span>
<span class="fw-code-copy">
  <span class="fw-code-copy-button">Copy</span>
  <code>&lt;link rel=&quot;stylesheet&quot; href=&quot;style-2.css&quot;&gt;</code>
</span>
<span class="fw-code-copy">
  <span class="fw-code-copy-button">Copy</span>
  <code>&lt;link rel=&quot;stylesheet&quot; href=&quot;style-3.css&quot;&gt;</code>
</span>