如何在文本区域的焦点上执行一次代码



我有一个这样的奶嘴:

$("textarea").on('focus', function(){
  alert("clicked");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea col="3" row="20"></textarea>

正如您在上面的小提琴中看到的,每次当您专注于该文本区域时,alert()都会执行。如何将其限制为仅执行一次?(第一次)

你可以

使用jQuery的one()

$("textarea").one('focus', function(){
  alert("clicked");
});

处理程序在每个事件类型的每个元素最多执行一次。

如果您

改变主意要触发焦点警报的次数,则可以这样使用计数器系统,只需更改 if then 语句值即可。

//initalize the counter
var count = 0;
//set the limit
var limit = 0;
//on focus event
$("textarea").on('focus', function(){
   //if the count equals the limit
   if(count === limit){
     //alert the message
     alert("clicked");
   }
//increment the count
count++;
});

最新更新