document.execCommand("Copy") 不复制

Kim*_*kim 2 jquery

我正在使用 jquery 使用户能够单击按钮来复制折扣代码。由于某种原因,document.execCommand("Copy");根本不起作用。当我ctrl + v粘贴时,什么也没有复制过来。有人可以帮我吗?谢谢!!

$(document).ready(function(){
$('#copyBtn').click(function(){

  console.log("loaded")
  var copyText = $('#discountCode');
  console.log($('#discountCode').text())
  copyText.select();
  document.execCommand("Copy");
  alert("Copied the text: " + copyText.text());
})

});
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>


	<p>Receive 20% discount on registration fees using the code: <strong><span id="discountCode">FKR2455EMSPN</span></strong></p>

	<p>
To register, you will be taken to the
SuperReturn website.
</p>
<p>
Click <button id="copyBtn">here </button> to copy our VIP code to your clipboard
</p>
<p>
Click <a href='#'>
here</a> to now be taken to the SuperReturn registration page.
</p>
</div>
Run Code Online (Sandbox Code Playgroud)

Adr*_*ni6 9

您缺少范围对象。

我在下面为您破解了代码并对其进行了评论,以便您可以确切地看到我在做什么。

var text = $("#discountCode").get(0); // Grab the node of the element

var selection = window.getSelection(); // Get the Selection object

var range = document.createRange(); // Create a new range

range.selectNodeContents(text); // Select the content of the node from line 1

selection.removeAllRanges(); // Delete any old ranges

selection.addRange(range); // Add the range to selection

document.execCommand('copy'); // Execute the command
Run Code Online (Sandbox Code Playgroud)

您的代码不起作用的原因是因为它没有突出显示您要复制的项目,因此您什么都不复制,并且当您什么都不复制时,您复制的最后一个值将被保留。

希望这可以帮助。

var text = $("#discountCode").get(0); // Grab the node of the element

var selection = window.getSelection(); // Get the Selection object

var range = document.createRange(); // Create a new range

range.selectNodeContents(text); // Select the content of the node from line 1

selection.removeAllRanges(); // Delete any old ranges

selection.addRange(range); // Add the range to selection

document.execCommand('copy'); // Execute the command
Run Code Online (Sandbox Code Playgroud)
$(document).ready(function(){
    $('#copyBtn').click(function(){

        var text = $("#discountCode").get(0)
        var selection = window.getSelection();
        var range = document.createRange();
        range.selectNodeContents(text);
        selection.removeAllRanges();
        selection.addRange(range);
        //add to clipboard.
        document.execCommand('copy');
    })
});
Run Code Online (Sandbox Code Playgroud)