Home  >  Article  >  Web Front-end  >  Solution to jquery selector that is not supported in setTimeout_javascript skills

Solution to jquery selector that is not supported in setTimeout_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:01:471319browse

When I was writing a js delay event today, I found that using jquery's $(this) in the setTimeout method did not work. After various tests, I finally concluded that jquery's selector is not supported in setTimeout. So I asked the jquery development experts on QQ for advice, and they solved the problem immediately. I will record it here.
The following is the js code used by the author when doing delayed processing:

$('.dl_select dt').hover( 
  function(){ 
    clearTimeout(t3); 
    $(this).siblings('dd').css({'display':'block','cursor':'pointer'}); 
  }, 
  function(){ 
    t2=setTimeout(function(){$(this).siblings('dd').css({'display':'none'});},300); 
  } 
); 
$('.dl_select dd').hover( 
  function(){ 
    clearTimeout(t2); 
    $(this).css({'display':'block','cursor':'pointer'}); 
  }, 
  function(){ 
    t3=setTimeout(function(){$(this).css({'display':'none'});},200); 
  } 
); 

Pay attention to the code in setTimeout in the above code. If these codes are not in this method, there is no problem in itself, but in this case, an error will be reported. As for the reason, the author has not figured it out yet. After being enlightened by netizens, I changed it to the following and it will be fine. The method is very clever. The following is the correct code:

$('.dl_select dt').hover( 
  function(){ 
    clearTimeout(t3); 
    $(this).siblings('dd').css({'display':'block','cursor':'pointer'}); 
  }, 
  function(){ 
    var $this=$(this).siblings('dd'); 
    t2=setTimeout(function(){$this.css({'display':'none'});},300); 
  } 
); 
$('.dl_select dd').hover( 
  function(){ 
    clearTimeout(t2); 
    $(this).css({'display':'block','cursor':'pointer'}); 
  }, 
  function(){ 
    var $this=$(this); 
    t3=setTimeout(function(){$this.css({'display':'none'});},200); 
  } 
); 

The above is the entire content of this article, I hope you all like it.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn