2016-08-05 10 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

というエラーを取得します。

また、​​の値に$(this)の値を$("#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、counter]を返し、結果[0]としてpPosを取得し、result [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

これは$(this)として var pPos = $(this).css('left');

ラインから来て、あなたの関数に定義されていません(関数は、そう、セレクタとは関係ありません$(これは)あなたが考えるように存在しません)。

$(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/

関連する問題