2016-11-14 85 views
-1

我想,當鼠標懸停找出元素的類,並且我得到一個試圖通過「本」作爲參數

TypeError: undefined is not an object (evaluating 'classString.split') 

控制檯錯誤。這是我的代碼。

function findClass(){ 
    var classString = $(this).attr('class'); 
    var myClass = classString.split(' ')[0]; 
    alert(myClass); 
} 

//blog 

$(".img2.blog").mouseenter(function() { 
    $('.img2.blog').css('opacity', '0'); 
    $('.img1.blog').removeClass('hidden'); 

    findClass(this); 

}); 

//albums 

$(".img2.albums").mouseenter(function() { 
    $('.img2.albums').css('opacity', '0'); 
    $('.img1.albums').removeClass('hidden'); 

    findClass(this); 
}); 

//videos 

$(".img2.videos").mouseenter(function() { 
    $('.img2.videos').css('opacity', '0'); 
    $('.img1.videos').removeClass('hidden'); 

    findClass(this); 
}); 

//contact 

$(".img2.contact").mouseenter(function() { 
    $('.img2.contact').css('opacity', '0'); 
    $('.img1.contact').removeClass('hidden'); 

    findClass(this); 
}); 

不知道如何通過「this」作爲參數。任何幫助讚賞。

回答

4

可以this,通過call方法:

findClass.call(this); 

很快會有人說,它也與apply一起工作。他們只是在如何將實際參數傳遞給函數(在需要的情況下)方面有所不同。

查看兩者的文檔。

,並添加同一家族的另外一種方式,與bind還可以實現它:

findClass.bind(this)(); 
3

你還是可以讓該函數知道參數是什麼:

function findClass(self) { 
    var classString = $(self).attr('class'); 
    var myClass = classString.split(' ')[0]; 
    alert(myClass); 
} 
0

使用callapply功能。 這裏有一個稍微修改的例子,演示如何做到這一點:

function findClass(){ 
    var classString = this['class']; 
    var myClass = classString.split(' ')[0]; 
    alert(myClass); 
} 

findClass.call({'class': "Hello World"}) 
findClass.apply({'class': "Hello World"})