可能重复:
jquery 将 $(this) 传递给其他函数
我正在编写一个 Javascript/jQuery 函数(尚未重构),但使用$(this)
. 解释起来有点困难,所以我将添加代码,希望它会变得更加清晰:
var accordion = 'div.accordionContent';
var accordButton = 'div.accordionButton';
var accordClosedArrow = 'url(/public/img/accordion-closed-arrow-';
var accordOpenArrow = 'url(/public/img/accordion-open-arrow-';
$(accordion).hide();
var accordFunc = function(arrowColor){
var img;
if ($(this).next(accordion).is(':visible')) {
img = accordClosedArrow + arrowColor + '.png)';
}
else {
img = accordOpenArrow + arrowColor + '.png)';
}
// these lines throw errors because of $(this)
$(this).css({backgroundImage:img}).next().slideToggle('slow').siblings(accordion)
.slideUp();
$(this).siblings()
.css({backgroundImage:accordClosedArrow + arrowColor + '.png)' + 'no-repeat'});
};
$(accordButton).live('click',function(){
accordFunc('blue');
});
$(accordButton + 'B').live('click',function(){
accordFunc('orange');
});
不知道为什么传递$(this)
会导致 Chrome 控制台抛出错误:
未捕获的类型错误:无法读取未定义的属性“firstChild”