按钮修改文本区域中的文本,然后复制修改后的文本

Button to modify text in the text area and then copy modified text

这是我的代码,但无法正常工作。

btn.addEventListener("click", function () {

  var get = document.getElementById('myTxtArea').value
  var res = get.split(/[ ,-]+/).join(';')
  textarea.innerText = res
  res.select();
  document.execCommand('copy');
})

W3: https://www.w3schools.com/howto/howto_js_copy_clipboard.asp

来自 SO 的另一个 post:

看来你把事情复杂化了,超出了他们需要的范围。试试这个:

function copy() {
  let textarea = document.getElementById("textarea");
  textarea.select();
  document.execCommand("copy");
}

function myFunction() {
  /* Get the text field */
  var copyText = document.getElementById("myInput");

  /* 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("Copied the text: " + copyText.value);
}

这个有效:

<textarea id="textarea">my value</textarea><br>
<button id="myButton" onclick="btnClick()">My Button</button>
//with jQuery
$(()=>{
    $("#myButton").click(()=>{
        let txtArea = $("#textarea");
        let txtVal = txtArea.val();
        // do something
        txtVal += " my added value";
        txtArea.val(txtVal);
        document.getElementById("textarea").select();
    });
});

//OR without jQuery

function btnClick() {
    let txtValue = document.getElementById("textarea").value;
    //do something
    txtValue += " add new value";
    document.getElementById("textarea").value = txtValue;
    document.getElementById("textarea").select();
}