如何在固定的时间内使用javascript函数

How to use javascript function in just fixed numbers of time?

本文关键字:javascript 函数 时间      更新时间:2023-09-26
<img src='plus.jpg' width='80' height='80' onclick="myFunction2()">

返回

function myFunction2() {
        var x = document.createElement("INPUT");
        x.setAttribute("name", "image[]");
        x.setAttribute("type", "file");
        document.getElementById("add").appendChild(x);
}

我想只使用 myFunction2() 4 次。之后,我想停止此功能。你能给我任何建议吗?提前谢谢。

试试这个:

var limit = 1;
function myFunction2() {
  if(limit <= 4){
   var x = document.createElement("INPUT");
   x.setAttribute("name", "image[]");
   x.setAttribute("type", "file");
   document.getElementById("add").appendChild(x);
   limit += 1;
  }else{
   alert("Stop");
  }
}

使用jQuery的解决方案。

var timesClicked = 0;
$( "#imgId" ).bind( "click", function( event ) {
  // do your operations here
  timesClicked++;
  if ( timesClicked >= 4 ) {
    $( this ).unbind( event );
  }
});
为什么

不使用计数器来检查点击次数何时达到 4,就像这样

.HTML:

<img src='plus.jpg' width='80' height='80' onclick="myFunction2()">

进入 JS

    var myCounter=0;  
    function myFunction2() {
if(myCounter <4){myCounter++;
            var x = document.createElement("INPUT");
            x.setAttribute("name", "image[]");
            x.setAttribute("type", "file");
            document.getElementById("add").appendChild(x);
}
    }