[英]jQuery .on() syntax and event.preventDefault()
假设我有以下代码行:
$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);
$comparePanel.on('click', '.pills li:not(.active)', toggleComparisonPanel(event);
有明显的语法错误(缺少“)”)。 固定到
$comparePanel.on('click', '.pills li:not(.active)', toggleComparisonPanel(event));
将附上toggleComparisonPanel(undefined)
的结果(假设此时没有可见的event
变量)。
你想做到
$comparePanel.on('click', '.pills li:not(.active)', toggleComparisonPanel);
function toggleComparisonPanel(event) {
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.