代码之家  ›  专栏  ›  技术社区  ›  P.Davide

使用jquery和jquery复制到剪贴板。复制到剪贴板。js问题

  •  0
  • P.Davide  · 技术社区  · 5 年前

    我正在使用jQuery脚本(copy to clipboard.js)将一些文本复制到剪贴板,然后粘贴到其他地方。

    包含我需要复制的行的页面是从数据库加载的。
    即使从数据库中删除一些行并使用Ajax调用将其从页面中删除,该脚本也能正常工作。

    当我使用Ajax调用向页面动态添加新行时,它停止工作。

    我的猜测是,我需要以某种方式包装代码或元素,但我不知道如何包装。你能帮帮我吗?

    这是我的jQuery代码:

    <script>
      $(document).ready(function(){
        $('.a_copy_img').click(function(){
            $(this).parents('#tlist > tr:first').find('td.text').CopyToClipboard();
          });
      });
    </script>
    

    这是页面中最初显示带有行的表的部分(它首先起作用):

    <div class="my-2">
                <table class="table">
                  <thead class="bg-light">
                    <tr>
                      <th scope="col">#</th>
                      <th scope="col">Immagine</th>
                      <th scope="col">Data</th>
                  <th scope="col">Copia</th>
                      <th scope="col">Cancella</th>
                    </tr>
                  </thead>
                  <tbody id="tlist">
                    <?php
    
                      $html = '';
                      $c = new Myclass();
                      $html = $c->list_imgs($pdo);
                      echo $html;
    
                    ?>
                  </tbody>
                </table>
    </div>
    

    这是显示上表行的函数的一部分:

    $this->html .= '<tr><th class="no_text" scope="row">' . $this->row['id'] . '</th><td class="text">' . $this->row['foto'] . '</td><td class="no_text">' . $this->row['reg_date'] . '<td class="text-center"><a class="a_copy_img" title="copia immagine" data-clipboard-target=".text" href="#" rel="' . $this->row['id'] . '"' . '><i class="fa fa-clone" aria-hidden="true"></i></a></td>' . '<td class="text-center"><a class="a_trash_img" title="cancella immagine" href="#" rel="' . $this->row['id'] . '"' . '><i class="fas fa-trash" aria-hidden="true"></i></a></td>' . '</tr>';
    
    0 回复  |  直到 5 年前
        1
  •  0
  •   P.Davide    5 年前

    我已经接近解决方案了,事实上,这是解决问题的正确jquery代码:

      <script>
        $(document).ready(function(){
          $(document).on("click", ".a_copy_img", function(){
              $(this).parents('#tlist > tr:first').find('td.text').CopyToClipboard();
            });
        });
      </script>
    

    解决方案是将事件绑定到文档中,现在它还可以与添加的元素一起工作。

    所以,希望它能帮助其他人找到解决这个问题或类似问题的方法。