将文本从隐藏的输入复制到剪贴板中

问题描述 投票:0回答:1

我试图通过按下按钮进行复制,将输入的值隐藏起来。在javascript中,该值是在var中获得的,没有任何问题,但它不会复制该值。我究竟做错了什么?谢谢

 <div class="dropdown-divider"></div>
  <a class="dropdown-item" onclick="mycopyphone()">Copiar Telefono</a>    
   <input type="hidden" id="Key" value="'. $row["telefono"] .'" />
     <script>
          function mycopyphone() {
           var hidden = document.getElementById("Key").value;
            copyText = hidden;
             copyText.select();
              copyText.setSelectionRange(0, 99999)
               document.execCommand("copy");
               alert("Copied the text: " + copyText.value);
                }
       </script>
javascript html input
1个回答
1
投票

两个问题。隐藏的输入不支持文本选择,而是具有select()函数的输入元素,而不是其值。您可以改为:

<div class="dropdown-divider"></div>
<a class="dropdown-item" onclick="mycopyphone()">Copiar Telefono</a>
<input type="text" style="display:none;" id="Key" value="'. $row["telefono"] .'" />
<script>
  function mycopyphone() {
    var hidden = document.getElementById("Key");
    hidden.style.display = 'block';
    hidden.select();
    hidden.setSelectionRange(0, 99999)
    document.execCommand("copy");
    alert("Copied the text: " + hidden.value);
    hidden.style.display = 'none';
  }
</script>
© www.soinside.com 2019 - 2024. All rights reserved.