2016-05-09 54 views
0

我試圖讓這個函數工作 - 但它沒有得到geht $(this)如果它被解僱了。我發現這個問題似乎是非常類似的問題(How to use $(this) in functions?),但我無法弄清楚爲什麼它不適用於我的情況。

如果有人能夠幫助我,那將會很棒。感謝

function scrolll(){ 
 
     var thiss = $(this).attr('id').substring(1); 
 
     var pos = $(this).scrollTop(); 
 
     // var next = Number(thiss) + 1; 
 
     // var prev = Number(thiss) - 1; 
 

 
     count = Number(thiss); 
 

 
     if (pos == 0) { 
 
      $(".section#s" + (count - 1)).removeClass("inactive", 1500, "linear"); 
 
      $(this).removeClass("active", 1500, "linear"); 
 
      var count = Number(thiss) - 1; 
 
     } 
 

 
     if($(this).scrollTop() + $(this).innerHeight() >= $(this)[0].scrollHeight) { 
 
      $(this).addClass("inactive", 1500, "linear"); 
 
      $(".section#s" + (count + 1)).addClass("active", 1500, "linear"); 
 
      var count = Number(thiss) + 1; 
 
      console.log("countbefore: " + count); 
 
      count++; 
 
      console.log("countafter: " + count); 
 
     } 
 
    } 
 

 

 

 

 
$('.section1').on('scroll', function() { 
 
     console.log(thiss) 
 
     scrolll($(this)); 
 
    }); 
 

 
$('.section2').on('scroll', function() { 
 
     console.log(thiss) 
 
     scrolll($(this)); 
 
    });

回答

0

最簡單的方法是將一個參數添加到scrolll並不擔心緊靠它,例如:

function scrolll(el) 
{ 
    var $this = $(el) 
    var thiss = $this.attr('id').substring(1); 

    .... etc 

$('.section2').on('scroll', function() { 
    scrolll(this); 
}); 

但你正在尋找的是call

function scrolll() 
{ 
    .... 

$('.section2').on('scroll', function() { 
    scrolll.call(this); 
}); 
+0

非常感謝,那正是我一直在尋找的。 - 它的工作。 –

0

$(this)在與選擇器的功能主要是使用。

E.g.

$('.button').click(function(){ 
$(this).css('color','red'); 
}); 

在這種情況下,$(this)將以.button選擇器爲目標。

+0

這正是方案它正在被使用,但希望將它傳遞給一個共同的功能。 –