我正在重构我的代码(我认为重构是正确的词),所以我使用了一个函数,这样我就不会重复太多。但我认为这个函数搞乱了我的 $(this)。
我的代码中注释掉的部分有效
我认为我的问题出在 disabled = this;
var active = '.teachers';
var disabled = '.teacher-link';
var width = $('.teachers .staff-outer-container').children().size() * 180;
$('.staff-outer-container').css('width', width + 'px');
/* BELOW IS COMMENTED OUT
$('.teacher-link').click(function() {
if (active != '.teachers') {
$(active).hide();
active = '.teachers';
$(active).show();
width = $('.teachers .staff-outer-container').children().size() * 180;
$('.teachers .staff-outer-container').css('width', width + 'px');
$(disabled).removeClass('active').addClass('clickable');
disabled = this;
$(disabled).removeClass('clickable').addClass('active');
$('#type').text('Teachers');
}
});
$('.admin-link').click(function() {
if (active != '.administrators') {
$(active).hide();
active = '.administrators';
$(active).show();
width = $('.administrators .staff-outer-container').children().size() * 180;
$('.administrators .staff-outer-container').css('width', width + 'px');
$(disabled).removeClass('active').addClass('clickable');
disabled = this;
$(disabled).removeClass('clickable').addClass('active');
$('#type').text('Administrators');
}
});
$('.support-link').click(function() {
if (active != '.support') {
$(active).hide();
active = '.support';
$(active).show();
width = $('.support .staff-outer-container').children().size() * 180;
$('.support .staff-outer-container').css('width', width + 'px');
$(disabled).removeClass('active').addClass('clickable');
disabled = this;
$(disabled).removeClass('clickable').addClass('active');
$('#type').text('Support Staff');
}
});
END COMMENT */
$('.teacher-link').click(function(){handle_click('.teachers','Teachers');});
$('.admin-link').click(function(){handle_click('.administrators','Administrators');});
$('.support-link').click(function(){handle_click('.support','Support Staff');});
function handle_click(target, target_text) {
if (active != target) {
$(active).hide();
active = target;
$(active).show();
width = $(target + ' .staff-outer-container').children().size() * 180;
$(target + ' .staff-outer-container').css('width', width + 'px');
$(disabled).removeClass('active').addClass('clickable');
disabled = this;
$(disabled).removeClass('clickable').addClass('active');
$('#type').text(target_text);
}
}
正如您从我的 fiddle 中看到的,点击后链接不会变成灰色。但如果我删除该函数并取消注释该脚本,它们就会再次工作。
最佳答案
this
根据您调用函数的方式设置。
当您调用 handle_click(...)
等普通函数时,this
将成为全局对象。
您可以通过调用 call
使用不同的 this
来调用该函数:
handle_click.call(customThis, arg1, arg2, ...);
或者,您可以将 this
作为普通参数传递,并在函数内使用该参数而不是 this
。
关于javascript - JQuery/Javascript 函数破坏了 $(this) (我认为),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16859600/