假设我有代码行:
$comparePanel.on('click', '.pills li:not(.active)', toggleComparisonPanel);
指向函数:
function toggleComparisonPanel() {
event.preventDefault();
$(this).addClass('active').siblings().removeClass('active');
$quickSpecsTable.toggleClass('comparison-mode');
$filters.toggle();
}
这在 Chrome 中有效,因为显然它将事件附加到窗口,使其成为全局的,据我所知。但是 Firefox 要求将事件传递给该函数。我已经尝试过但没有成功:
$comparePanel.on('click', '.pills li:not(.active)', toggleComparisonPanel(event);
function toggleComparisonPanel(event) {
event.preventDefault();
$(this).addClass('active').siblings().removeClass('active');
$quickSpecsTable.toggleClass('comparison-mode');
$filters.toggle();
}
这样的事情是否可能,或者是我将代码放入 .on() 函数内的匿名函数的唯一选择,如以下代码?
$comparePanel.on('click', '.pills li:not(.active)', function(event){
event.preventDefault();
$(this).addClass('active').siblings().removeClass('active');
$quickSpecsTable.toggleClass('comparison-mode');
$filters.toggle();
});
如果可能的话,我宁愿将事件处理程序和函数分开。老实说,除了让我感觉更整洁之外,可能没有太多原因,但这样做会很好
最佳答案
您可以简单地在其他地方声明该函数,如下所示:
// declare event here, since you're using it here
function toggleComparisonPanel(event) {
event.preventDefault();
$(this).addClass('active').siblings().removeClass('active');
$quickSpecsTable.toggleClass('comparison-mode');
$filters.toggle();
}
// just pass the function here
$comparePanel.on('click', '.pills li:not(.active)', toggleComparisonPanel);
关于javascript - jQuery .on() 语法和 event.preventDefault(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8533066/