使用.select()将文本复制到剪贴板,获取未捕获的TypeError

Eri*_*yen 3 javascript

我正在尝试遵循以下代码:https : //www.w3schools.com/howto/howto_js_copy_clipboard.asp

HTML模态:

<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
      <div class="modal-dialog" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
            <h4 class="modal-title" id="myModalLabel">App Link</h4>
          </div>
          <div class="modal-body">
            <input id="appID" value="123"></input>
            <button type="button" class="btn btn-success" id="copyBtn">Copy</button>
            </div>                  
        </div>
      </div>
    </div>
Run Code Online (Sandbox Code Playgroud)

这是我的JS:

var copyBtn = document.getElementById('copyBtn');

copyBtn.onclick = function(){
    var myCode = document.getElementById('appID').value;
    var fullLink = document.createElement('input');
    document.body.appendChild(fullLink);
    fullLink.value = "http://fulllink/" + myCode;
    fullLink.select();
    document.execCommand("copy", false);
    fullLink.remove();
    alert("Copied the text: " + fullLink.value);
}
Run Code Online (Sandbox Code Playgroud)

Code will not work when input and button are inside the modal; code will work if placed in the body. Why?

Phi*_*mas 9

您正在收到错误,因为.select该函数绑定到输入元素。您当前正在尝试在fullLink字符串上调用select 。我们需要创建一个输入元素并为其提供值。像这样:

var copyBtn = document.getElementById('copyBtn');
copyBtn.onclick = function(){
    var myCode = document.getElementById('appID').value;
    var fullLink = document.createElement('input');
    document.body.appendChild(fullLink);
    fullLink.value = "http://fulllink/" + myCode;
    fullLink.select();
    document.execCommand("copy", false);
    fullLink.remove();
    alert("Copied the text: " + fullLink.value);
}
Run Code Online (Sandbox Code Playgroud)
<input id="appID" value="123"></input>
<button id="copyBtn">Copy</button>
Run Code Online (Sandbox Code Playgroud)