javascript - jQuery .on() 语法和 event.preventDefault()

标签 javascript jquery

假设我有代码行:

$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/

相关文章:

javascript - Cordova run --debug 构建空白应用程序

javascript - Cordova /电话间隙 : AJAX calls not working on iOS device

javascript - 使用 Google map 创建点密度图

javascript - Jquery 1.10.2 跨域请求

javascript - 在二维网格中查找相邻的图 block

JavaScript方法和属性调用区别混淆

javascript - 使用 onclick 从表的 td 调用 jquery 函数

javascript - jquery 创建一个不会消失的工具提示

javascript - Jquery - 自动将当年月份添加到下拉列表

javascript - javascript/jquery 中函数的执行