gpt4 book ai didi

jquery - document.execCommand ("Copy") 不复制

转载 作者:行者123 更新时间:2023-12-01 06:26:01 24 4
gpt4 key购买 nike

我正在使用 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());
})

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

最佳答案

您缺少范围对象。

我在下面为您破解了代码并对其进行了评论,以便您可以准确地看到我所做的事情。

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

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

希望这有帮助。

$(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');
})
});
<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>

关于jquery - document.execCommand ("Copy") 不复制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47421025/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com