首页 > 解决方案 > 将文本从表格中的特定数据单元格复制到剪贴板。

问题描述

我正在尝试在我的 php 文件中使用 JavaScript 函数从表中的特定单元格复制数据。每行都有一列用于项目、描述和项目链接。

我希望能够通过单击按钮将链接复制到剪贴板。但是,无论我单击哪一行复制链接,它都只复制最后一个。

我的 Javascript 函数只接受表格上显示的最后一个 ID 变量,而不是我要复制的变量的 ID...

        while ($row = $result->fetch_assoc()) {
        $id = $row['id'];
                echo '<tr align="center">
                        <td>'.$row["pid"].':<br>'.$row["pname"].'</td>
                        <td>' .$row["URLdescription"].'</td>
                        <td>
                                <input type="text" value="'.$row['directionsURL'].'" id="'.$id.'">
                                <button onclick="myFunction()" name="copy"> Copy </button>
                        </td>
                     </tr>';
    };   //  END WHILE

^^ 这是我的while循环

    <script>
        function myFunction() {
          var copyText = document.getElementById("<?php echo $id; ?>")
          copyText.select();
          document.execCommand("copy");
          alert("Copied the text: " + copyText.value);
        }
</script>

^^这是我的 JavaScript 函数。

标签: javascriptphpvariables

解决方案


html

<input type="text" value="
<?php echo $row['account']; ?>" id="
<?php echo "myInput".$id ;?>"> 
            
<button class = "abc btn-sm btn-success" data-id1="
    <?php echo "myInput".$id ;?>">
            Copy
            
</button>

JS

  $(document).on('click', '.abc', function(){  
    var id = $(this).data("id1");
            
    var copyText = document.getElementById(id);

    /* Select the text field */
    copyText.select();
    copyText.setSelectionRange(0, 99999); /*For mobile devices*/

    /* Copy the text inside the text field */
    document.execCommand("copy");

    /* Alert the copied text */
     alert("Copy: " + copyText.value);

}); 

推荐阅读