2016-08-05 76 views
3

我的代码是:

$(document).ready(function(){ 

    var hCount = 0, 
     eCount = 0, 
     nCount = 0, 
     mCount = 0; 

$("#head").click(function() { 
     var pPos = counter(hCount); 
     $(this).animate({left:pPos+"px"}, 1000); 
    }); 

function counter(count) 
{ 
    count++; 
    if(count === 10) 
    { 
     count = 0; 
     pPos = 0; 
    } 
    else 
    { 
     var pPos = $(this).css('left'); 
     pPos = pPos.substring(0,(pPos.length-2)) 
     pPos -= 367; 

    } 

    return pPos; 
} 

我得到一个错误,说明

Uncaught TypeError: Cannot read property 'defaultView' of undefined

我不知道是什么导致了这个错误。

另外,如何将counter()的功能的值传递给$("#head").click?我不能直接提到$("#head"),因为我会在重复使用函数计数器中的代码的同时使用除#head之外的更多div来重复此功能。

+0

请不要问多个问题。问一个或另一个 – Liam

回答

6

只是延长反函数elem参数,点击操作中传递:

function counter(count, elem){ 
    // ... 
} 

$("#head").click(function() { 
    var elem = $(this); 
    var pPos = counter(hCount, elem); 
    elem.animate({left:pPos+"px"}, 1000); 
}); 
+0

谢谢,但现在显然我有一个新问题。我需要从函数计数器传递'pPos'和'count'的值,而不使用全局变量。任何想法可以做什么? –

+1

从计数器返回列表:返回[pPos,计数器],并获得pPos作为结果[0]并计为结果[1],其中result = counter() –

+0

最后一个问题,先生..有什么办法可以消除全局变量hCount,eCount,nCount和mCount? –

3

$(this)就像任何其他的对象。只需将它传递给你的函数:

counter(hCount, $(this)); 
.... 

function counter(count, thisFromPreviousFunction) 
3

Uncaught TypeError: Cannot read property 'defaultView' of undefined

这来自 var pPos = $(this).css('left');

$(this)没有在你的函数定义(该功能不相关的一个选择的路线,所以$(this)不存在,因为你认为)。

$(document).ready(function(){ 

    var hCount = 0, 
     eCount = 0, 
     nCount = 0, 
     mCount = 0; 

    $("#head").click(function() { 
    var pPos = counter(hCount, $(this)); // Pass the selector 
    $(this).animate({left:pPos+"px"}, 1000); 
    }); 

    function counter(count, selector) { 
     count++; 
     if(count === 10) { 
      count = 0; 
      pPos = 0; 
     } 
     else { 
      var pPos = selector.css('left'); // Use the given selector 
      pPos = pPos.substring(0,(pPos.length-2)) 
      pPos -= 367; 
     } 
     return pPos; 
    } 
}); 

https://jsfiddle.net/yw2b4tyt/