Possible Duplicate:
jquery passing $(this) to other functions
我寫一個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瀏覽器控制檯拋出一個錯誤:
Uncaught TypeError: Cannot read property 'firstChild' of undefined
親愛的主,把'$(this)'包裝一次並重用它。 – jbabey