AngliaXu
 1 <!DOCTYPE html>
 2 <html>
 3     <head>
 4         <meta charset="UTF-8">
 5         <title></title>
 6     </head>
 7     <body>
 8         <input type="text" />
 9         <span>0</span><em>字</em>
10         <ul></ul>
11 <script src="jquery-3.2.1.min.js" type="text/javascript" charset="utf-8"></script>
12 <script type="text/javascript">
13 
14 $(\'input:eq(0)\').keydown(function(ev){
15     //判断条件不对,因为每当input输入的时候,开启了多个定时器,关的时候不知道关的是那个定时器,
     但是如果我只输入一个字符的时候,就可以关闭定时器了。
16 if(ev.keyCode!=13){ 17 timer=setInterval(function(){ 18 $(\'span\').text($(\'input\').val().length); 19 console.log(111); 20 },40) 21 }else{ 22 clearInterval(timer); 23 } 24 25 }) 26 $(\'input:eq(0)\').keyup(function(ev){ 27 28 if(ev.keyCode==13){ 29 var x=$(\'<li>\'+$(\'input\').val()+\'</li>\'); 30 $(\'ul\').append(x); 31 $(\'input\').val(\'\'); 32 $(\'span\').text(\'0\'); 33 clearInterval(timer); 34 } 35 }) 36 </script> 37 38 </body> 39 </html>

    上面的方法是错误的,原因在于每次输入的时候都开启了一个定时器,最后关闭的时候不知道该关闭哪一个定时器。下面这个方法是可取的

 1 var timer=null;
 2     $(\'input:eq(0)\').focus(function(){
 3         timer=setInterval(function(){
 4             $(\'span\').text($(\'input\').val().length);
 5             console.log(111);
 6         },40)
 7         
 8     })
 9     $(\'input:eq(0)\').keyup(function(ev){
10         if(ev.keyCode==13){
11             var x=$(\'<li>\'+$(\'input\').val()+\'</li>\');
12             $(\'ul\').append(x);
13             $(\'input\').val(\'\');
14             $(\'span\').text(\'0\');
15             clearInterval(timer);
16             timer=null;
17         }else{
18             if(!timer){
19                 timer=setInterval(function(){
20             $(\'span\').text($(\'input\').val().length);
21             console.log(111);
22         },40)
23             }
24         }
25     })

 

分类:

技术点:

相关文章:

  • 2021-12-14
  • 2021-12-18
  • 2021-11-03
  • 2021-09-20
  • 2021-11-19
  • 2022-01-06
  • 2021-08-21
  • 2021-12-31
猜你喜欢
  • 2021-05-11
  • 2021-12-24
  • 2021-12-03
  • 2021-12-24
  • 2021-04-13
  • 2021-12-18
  • 2021-06-30
相关资源
相似解决方案