在后端复制 Wordpress 标题

Copy Wordpress Title in backend

所以,我有一个 CPT,并且在后端添加了一些自定义列。我在旁边有这个按钮,它应该复制标题。我为此使用 Javascript,但它不起作用。

function myFunction() {
  var copyText = document.getElementById("clickTitle");
  copyText.select();
  document.execCommand("copy");
  alert("Copied the text: " + copyText.value);
}
.click-title{
display: none;
}
echo the_title( '<h4 class="click-title" id="clickTitle">', '</h4>' );
echo '<button class="btn btn-danger btn-sm" onclick="copyFunction()">Copy Title</button>';

但它不起作用。我想让按钮复制标题,但我找不到办法做到这一点。我尝试了不止这些。

(Click here to view image) I want to copy the title when I click Copy Title button.

Select 仅适用于输入文本字段元素

因此,在您的标题旁边设置一个 input 隐藏字段。

function copyFunction() {
  var copyText = document.getElementById("clickTitle");
  copyText.select();
  document.execCommand("copy");
  alert(copyText.value);
}
<h4 class="click-title">This is the title to be copied.</h4>
<input id="clickTitle" type="text" value="This is the title to be copied">
<button class="btn btn-danger btn-sm" onclick="copyFunction()">Copy Title</button>

要在循环内工作,应该做一点改变。

为每个输入字段指定唯一 ID:

<input id="clickTitle-<?php echo $post_id; ?>" type="text" value="This is the title to be copied">

通过传递所需的 ID 来调用方法:

<button class="btn btn-danger btn-sm" onclick="copyFunction(<?php echo $post_id; ?>)">Copy Title</button>

然后更新函数以查找正确的 ID。

function copyFunction( elId ) {
  var copyText = document.getElementById("clickTitle-" + elId );
  ...
}