我的代码是:
$(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;
}
我收到一个错误,说明
未捕获的类型错误:无法读取未定义的属性"defaultView">
我不知道是什么导致了这个错误。
此外,如何将函数counter()
传递给$("#head").click
中$(this)
的值?我不能直接提到$("#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);
});
未捕获的类型错误:无法读取未定义的属性"defaultView">
这来自线路var pPos = $(this).css('left');
因为$(this)
没有在函数中定义(该函数与Selector无关,所以$(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/
$(this)
和其他对象一样,只是一个对象。只需将其传递到您的函数:
counter(hCount, $(this));
....
function counter(count, thisFromPreviousFunction)