簡體   English   中英

如何避免javascript中的代碼重復

[英]how to avoid code repetition in javascript

我有重復的 javascript 代碼,我想讓它變小或

 <script type="text/javascript">
    function myFunction1() {
  var copyText = document.getElementById("myInput1");
  copyText.select();
  document.execCommand("copy");

}
</script>
<script type="text/javascript">
  function myFunction2() {
  var copyText = document.getElementById("myInput2");
  copyText.select();
  document.execCommand("copy");

}
</script>
<script type="text/javascript">
  function myFunction3() {
  var copyText = document.getElementById("myInput3");
  copyText.select();
  document.execCommand("copy");

}
</script>

並用循環將變量放入函數名中

謝謝你

創建一個函數,傳遞元素 id 並將其用於獲取 copyText 對象。

<script type="text/javascript">
  function myFunction(elementId) {
    var copyText = document.getElementById(elementId);
    copyText.select();
    document.execCommand("copy");
  }
</script>

並像這樣調用它。

 myFunction("myInput1");
 myFunction("myInput2");
 myFunction("myInput3");

您可以創建具有良好名稱的單個函數。

<script type="text/javascript">
  function copyInputsValueToClipboard(elementId){
    const element = document.getElementById(elementId);
    element.select();
    document.execCommand("copy");
  }
</script>

然后,您可以使用要復制到剪貼板的輸入的id調用該函數。

copyInputsValueToClipboard("myInput1");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM