jquery 在JavaScript中复制到剪贴板无法正常工作

wbrvyc0a  于 2023-08-04  发布在  jQuery
关注(0)|答案(1)|浏览(168)

我有以下代码:

$(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) {
            // Create a temporary input element
            var $tempInput = $('<input type="text">');
            $('body').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('copy');

            // Remove the temporary input element
            $tempInput.remove();

            alert("Copied the text: " + text);
        }

个字符
我的问题是,当我按下按钮复制到剪贴板,在警报和我的剪贴板有一个四舍五入的ID即使它是一个字符串,前两个数字的变化。例:第一个(76561199144601203)给我这个“76561199144601200”
它不应该改变任何东西,它只应该被复制到剪贴板。我尝试了其他方法,如navigator.clipboard.writeText(),但结果是一样的。
我做错了什么?有人能帮忙吗?

pgx2nnw8

pgx2nnw81#

稍微修改一下CopyIdToClipboard函数,使用button元素获取文本,尝试下面的可运行示例。
基本上所有的变化都在JavaScript处理中:
1.在添加按钮的循环中,onclick事件更改为:onclick="CopyIdToClipboard(this)" ...(this是对button元素本身的引用)

  1. CopyIdToClipboard的参数从text更改为element(因为它现在是元素引用,而不是文本)
    1.对于val(),button元素的textContent被设置为值。(按钮的文本)
$(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) {
            // Create a temporary input element
            var $tempInput = $('<input type="text">');
            $('body').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('copy');

            // Remove the temporary input element
            $tempInput.remove();

            alert("Copied the text: " + element.innerHTML);
        }

个字符

相关问题