在JavaScript中复制到剪贴板不正常工作。

huangapple go评论69阅读模式
英文:

Copy to clipboard in javascript doesn't work properly

问题

我有以下的代码:

<!-- 开始代码片段: js 隐藏: false 控制台: true Babel: false -->

<!-- 语言: lang-js -->
$(document).ready(function () {
    var usernames = ["user1", "user2", "user3", "user4", "user5", "user6", "user7"];
    var ids = ["76561199144601203", "76561199085110484", "76561199202629307", "76561198977492126", "76561199107090117", "76561199156985347", "76561199195037086"];
    var part = '';
    for (var i = 0; i < usernames.length; i++) {
        $('#user_id_table > tbody:last-child').append('<tr><th scope="row">' + usernames[i] + '</th><td><button onclick="CopyIdToClipboard(' + ids[i] + ')">' + ids[i] + '</button></td></tr>');
    }
});

function CopyIdToClipboard(text) {
    // 创建一个临时输入元素
    var $tempInput = $('<input type="text">');
    $('body').append($tempInput);

    // 设置临时输入元素的值为文本
    $tempInput.val(text).select();

    // 复制文本到剪贴板
    document.execCommand('copy');

    // 删除临时输入元素
    $tempInput.remove();

    alert("已复制文本:" + text);
}

<!-- 语言: lang-html -->
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Bootstrap示例</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet"
        integrity="sha384-9ndCyUaIbzAi2FUVXJi0CjmCapSmO7SnpJef0486qhLnuZ2cdeRhO02iuK6FUUVM" crossorigin="anonymous">
</head>

<body>
    <!-- Jquery -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

    <div class="container">
        <div class="row">
            <table class="table border" id="user_id_table">
                <thead>
                    <tr>
                        <th scope="col">用户名</th>
                        <th scope="col">ID</th>
                    </tr>
                </thead>
                <tbody>
                </tbody>
            </table>
        </div>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"
        integrity="sha384-geWF76RCwLtnZ8qwWowPQNguL3RmwHVBC9FhGdlKrxdiJJigb/j/68SIy3Te4Bkz"
        crossorigin="anonymous"></script>
</body>

</html>

<!-- 结束代码片段 -->

我的问题是,当我按下复制到剪贴板的按钮时,在警告框和我的剪贴板中,ID 会四舍五入,即使它是一个字符串,前两个数字会变化。

示例:第一个(76561199144601203)给我这个“76561199144601200”

它不应该改变任何东西,只应该复制到剪贴板。我尝试了其他方法,如navigator.clipboard.writeText(),但结果是相同的。

我做错了什么?有人可以帮忙吗?

英文:

I have the following code:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

$(document).ready(function () {
var usernames = [&quot;user1&quot;, &quot;user2&quot;, &quot;user3&quot;, &quot;user4&quot;, &quot;user5&quot;, &quot;user6&quot;, &quot;user7&quot;];
var ids = [&quot;76561199144601203&quot;, &quot;76561199085110484&quot;, &quot;76561199202629307&quot;, &quot;76561198977492126&quot;, &quot;76561199107090117&quot;, &quot;76561199156985347&quot;, &quot;76561199195037086&quot;];
var part = &#39;&#39;;
for (var i = 0; i &lt; usernames.length; i++) {
$(&#39;#user_id_table &gt; tbody:last-child&#39;).append(&#39;&lt;tr&gt;&lt;th scope=&quot;row&quot;&gt;&#39; + usernames[i] + &#39;&lt;/th&gt;&lt;td&gt;&lt;button onclick=&quot;CopyIdToClipboard(&#39; + ids[i] + &#39;)&quot;&gt;&#39; + ids[i] + &#39;&lt;/button&gt;&lt;/td&gt;&lt;/tr&gt;&#39;);
}
});
function CopyIdToClipboard(text) {
// Create a temporary input element
var $tempInput = $(&#39;&lt;input type=&quot;text&quot;&gt;&#39;);
$(&#39;body&#39;).append($tempInput);
// Set the value of the temporary input element to the text
$tempInput.val(text).select();
// Copy the text to the clipboard
document.execCommand(&#39;copy&#39;);
// Remove the temporary input element
$tempInput.remove();
alert(&quot;Copied the text: &quot; + text);
} 

<!-- language: lang-html -->

&lt;!doctype html&gt;
&lt;html lang=&quot;en&quot;&gt;
&lt;head&gt;
&lt;meta charset=&quot;utf-8&quot;&gt;
&lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1&quot;&gt;
&lt;title&gt;Bootstrap demo&lt;/title&gt;
&lt;link href=&quot;https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css&quot; rel=&quot;stylesheet&quot;
integrity=&quot;sha384-9ndCyUaIbzAi2FUVXJi0CjmCapSmO7SnpJef0486qhLnuZ2cdeRhO02iuK6FUUVM&quot; crossorigin=&quot;anonymous&quot;&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;!-- Jquery --&gt;
&lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js&quot;&gt;&lt;/script&gt;
&lt;div class=&quot;container&quot;&gt;
&lt;div class=&quot;row&quot;&gt;
&lt;table class=&quot;table border&quot; id=&quot;user_id_table&quot;&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th scope=&quot;col&quot;&gt;USERNAME&lt;/th&gt;
&lt;th scope=&quot;col&quot;&gt;ID&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;script src=&quot;https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js&quot;
integrity=&quot;sha384-geWF76RCwLtnZ8qwWowPQNguL3RmwHVBC9FhGdlKrxdiJJigb/j/68SIy3Te4Bkz&quot;
crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;

<!-- end snippet -->

My problem is when I press the button to copy to clipboard, in the alert and in my clipboard there is a round up of the ID even if it is a string, the first two numbers change.
Example: The first one(76561199144601203) gives me this "76561199144601200"

It shouldn't change anything, it should only get copied to the clipboard.
I tried other approches like navigator.clipboard.writeText() but the result is the same.

What I'm doing wrong? Anyone can help?

答案1

得分: 0

CopyIdToClipboard函数进行了轻微的修改,以使用按钮元素获取文本,试试下面的可运行示例。

基本上,所有更改都在JavaScript处理中:

  1. 在添加按钮的循环中,onclick事件更改为:onclick=&quot;CopyIdToClipboard(this)&quot;...(this是对按钮元素本身的引用)
  2. CopyIdToClipboard的参数从text更改为element(因为现在它是一个元素引用,而不是文本)
  3. 对于val(),将按钮元素的textContent设置为值。(按钮的文本)
<!-- begin snippet: js hide: false console: true babel: null -->

<!-- language: lang-js -->
$(document).ready(function () {
    var usernames = ["user1", "user2", "user3", "user4", "user5", "user6", "user7"];
    var ids = ["76561199144601203", "76561199085110484", "76561199202629307", "76561198977492126", "76561199107090117", "76561199156985347", "76561199195037086"];
    var part = '';
    for (var i = 0; i < usernames.length; i++) {
        $('#user_id_table > tbody:last-child').append('<tr><th scope="row">' + usernames[i] + '</th><td><button onclick="CopyIdToClipboard(this)">' + ids[i] + '</button></td></tr>');
    }
});

function CopyIdToClipboard(element) {
    // 创建临时输入元素
    var $tempInput = $('<input type="text">');
    $('body').append($tempInput);

    // 将临时输入元素的值设置为文本
    $tempInput.val(element.textContent).select();
             // 注意,.innerHTML 也可以工作

    // 将文本复制到剪贴板
    document.execCommand('copy');

    // 删除临时输入元素
    $tempInput.remove();

    alert("已复制文本:" + element.innerHTML);
}
<!-- language: lang-html -->
<!doctype html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Bootstrap demo</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet"
        integrity="sha384-9ndCyUaIbzAi2FUVXJi0CjmCapSmO7SnpJef0486qhLnuZ2cdeRhO02iuK6FUUVM" crossorigin="anonymous">
</head>

<body>
    <!-- Jquery -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

    <div class="container">
        <div class="row">
            <table class="table border" id="user_id_table">
                <thead>
                    <tr>
                        <th scope="col">USERNAME</th>
                        <th scope="col">ID</th>
                    </tr>
                </thead>
                <tbody>
                </tbody>
            </table>
        </div>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"
        integrity="sha384-geWF76RCwLtnZ8qwWowPQNguL3RmwHVBC9FhGdlKrxdiJJigb/j/68SIy3Te4Bkz"
        crossorigin="anonymous"></script>
</body>

</html>

英文:

With some slight rework of the CopyIdToClipboard function to use the button element to get the text, try the runnable example below.

Basically the changes are all in the javascript handling:

  1. In the loop where the buttons are added, the onclick event changes to: onclick=&quot;CopyIdToClipboard(this)&quot; ... (this is a reference to the button element itself)
  2. The parameter to CopyIdToClipboard changes from text to element (as it is now an element reference, and not text)
  3. To the val(), the button element's textContent is set as the value. (the button's text)

<!-- begin snippet: js hide: false console: true babel: null -->

<!-- language: lang-js -->

$(document).ready(function () {
var usernames = [&quot;user1&quot;, &quot;user2&quot;, &quot;user3&quot;, &quot;user4&quot;, &quot;user5&quot;, &quot;user6&quot;, &quot;user7&quot;];
var ids = [&quot;76561199144601203&quot;, &quot;76561199085110484&quot;, &quot;76561199202629307&quot;, &quot;76561198977492126&quot;, &quot;76561199107090117&quot;, &quot;76561199156985347&quot;, &quot;76561199195037086&quot;];
var part = &#39;&#39;;
for (var i = 0; i &lt; usernames.length; i++) {
$(&#39;#user_id_table &gt; tbody:last-child&#39;).append(&#39;&lt;tr&gt;&lt;th scope=&quot;row&quot;&gt;&#39; + usernames[i] + &#39;&lt;/th&gt;&lt;td&gt;&lt;button onclick=&quot;CopyIdToClipboard(this)&quot;&gt;&#39; + ids[i] + &#39;&lt;/button&gt;&lt;/td&gt;&lt;/tr&gt;&#39;);
}
});
function CopyIdToClipboard(element) {
// Create a temporary input element
var $tempInput = $(&#39;&lt;input type=&quot;text&quot;&gt;&#39;);
$(&#39;body&#39;).append($tempInput);
// Set the value of the temporary input element to the text
$tempInput.val(element.textContent).select();
// note that .innerHTML works too
// Copy the text to the clipboard
document.execCommand(&#39;copy&#39;);
// Remove the temporary input element
$tempInput.remove();
alert(&quot;Copied the text: &quot; + element.innerHTML);
} 

<!-- language: lang-html -->

&lt;!doctype html&gt;
&lt;html lang=&quot;en&quot;&gt;
&lt;head&gt;
&lt;meta charset=&quot;utf-8&quot;&gt;
&lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1&quot;&gt;
&lt;title&gt;Bootstrap demo&lt;/title&gt;
&lt;link href=&quot;https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css&quot; rel=&quot;stylesheet&quot;
integrity=&quot;sha384-9ndCyUaIbzAi2FUVXJi0CjmCapSmO7SnpJef0486qhLnuZ2cdeRhO02iuK6FUUVM&quot; crossorigin=&quot;anonymous&quot;&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;!-- Jquery --&gt;
&lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js&quot;&gt;&lt;/script&gt;
&lt;div class=&quot;container&quot;&gt;
&lt;div class=&quot;row&quot;&gt;
&lt;table class=&quot;table border&quot; id=&quot;user_id_table&quot;&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th scope=&quot;col&quot;&gt;USERNAME&lt;/th&gt;
&lt;th scope=&quot;col&quot;&gt;ID&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;script src=&quot;https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js&quot;
integrity=&quot;sha384-geWF76RCwLtnZ8qwWowPQNguL3RmwHVBC9FhGdlKrxdiJJigb/j/68SIy3Te4Bkz&quot;
crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年7月14日 07:06:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/76683780.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定