简体   繁体   中英

Javascript - Onclick() function only works once

I'm making a function to copy an editable div's content from the acess.php file. The function works well, but if I edit the div and click on the copy button again, it doesn't work anymore until I restart the page. There is more text to be copied but I reduced for privacy reasons.

copy.js file:

document.querySelector("#foo").onclick = function() {
    var divToCopy = document.querySelector("#selectPage");

    var range = document.createRange();
    range.selectNode(divToCopy);
    window.getSelection().addRange(range);
    document.execCommand("copy");
};

acess.php file:

<head>
  <button id="foo">Copy</button>
  <meta charset="utf-8" />
  <title>Acess</title>
  <script src="../../js/jquery.js"></script>
  <script src="../../js/copy.js"></script>
  <link rel="stylesheet" href="../css/sit.css">
</head>

<body>
  <div contenteditable="true" id="bodyEmail" style="border: solid 0.5px black; padding:1%; margin-top: 20px">
    <div id="selectPage">
      <main>
        <h1 class='h1-principal'> Text to be copied <strong class='sub'><?= $func['SOLIC'] ?></strong></h1>
        <p>Text to be copied <strong class='sub'><?= $name['NAME'] ?></strong> Text to be copied <strong class='sub'><?= $dateAdmin ?></strong></p>
       </main>
    </div>
</div>

In acess.php file you added button in head tag it should be in body tag.

You can select content using selectAll command

 document.querySelector("#foo").onclick = function() { document.execCommand('selectAll',false,null); document.execCommand("copy"); };
 <div contenteditable="true" id="bodyEmail" style="border: solid 0.5px black; padding:1%; margin-top: 20px"> <div id="selectPage"> <main> <h1 class='h1-principal'> Text to be copied <strong class='sub'><?= $func['SOLIC']?></strong></h1> <p>Text to be copied <strong class='sub'><?= $name['NAME']?></strong> Text to be copied <strong class='sub'><?= $dateAdmin?></strong></p> </main> </div> </div> <button id="foo">Copy</button>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM