2015-11-08 20 views
1

這是我在jQuery中的代碼。我有一個按鈕(class =「trail」),以及class =「cell」的div網格。如果當前單元格沒有內部div,我會在其中添加一個內部div。否則,我淡入其中。方法.children()的長度在函數內部和外部的行爲不同

一切正常。但是當我試圖把這個代碼放在一個單獨的函數中時,出於某種原因,變量divnum給了我一個結果2(在我第一次輸入的單元格中,所以它應該是0,而不是2)。

如果代碼外的函數divnum只能是等於0或1

誰能給我解釋一下哪裏這個divnum = 2來自當我把我的代碼的var MyFunction = function(){};

「警報」我只用於調試。

$('#trail').on('click', function(){ //when i press this button 
    $('.cell').mouseenter(function(){ 
     divnum = $(this).children().length; //check if the div i enter has inner divs in it 
     if (divnum == 0) { 
      alert('divnum') 
      $(this).append('<div class="fade"></div>');} //if not - add a div 
     else { 
      //alert(divnum) 
      $(this).children().fadeIn(10); //if it has children, fade them in 
     } 
     $('.fade').width(CellSize).height(CellSize); //giving a size to the div that was appended 
     $('.fade').mouseleave(function(){ 
      $(this).fadeOut(1000); //fade out the appended div 
     }); 

    }); 
}); 
+0

我upvote這個有用的問題! –

回答

0

你的問題是在Javascript中對this的引用。在jQuery事件中,它將被設置爲正確的DOM元素。檢查這是否工作:

function process(reference) { 
    divnum = $(reference).children().length; //check if the div i enter has inner divs in it 
    if (divnum == 0) { 
     alert('divnum') 
     $(reference).append('<div class="fade"></div>');} //if not - add a div 
    else { 
     //alert(divnum) 
     $(reference).children().fadeIn(10); //if it has children, fade them in 
    } 
    $('.fade').width(CellSize).height(CellSize); //giving a size to the div that was appended 
    $('.fade').mouseleave(function(){ 
     $(reference).fadeOut(1000); //fade out the appended div 
    }); 
} 
$('#trail').on('click', function(){ //when i press this button 
    $('.cell').mouseenter(function(){ 
     process(this); 
    }); 
}); 
相關問題