jQuery .on() syntax and event.preventDefault()

jQuery .on() syntax and event.preventDefault()

本文关键字:event preventDefault and syntax jQuery on      更新时间:2023-09-26

假设我有一行代码:

$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) {
...
}