我的代码是:
$(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()
$(this)
的值在$("#head").click
?我不能直接提到 $("#head")
因为除了 #head
之外,我会用更多的 div 重复这个功能,同时重用函数计数器中的代码。
最佳答案
只需使用 elem
参数扩展计数器函数并在点击处理中传递它:
function counter(count, elem){
// ...
}
$("#head").click(function() {
var elem = $(this);
var pPos = counter(hCount, elem);
elem.animate({left:pPos+"px"}, 1000);
});
关于javascript - 如何将 $(this) 传递给函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38786114/