简体   繁体   中英

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

Supposing I have the line of code:

$comparePanel.on('click', '.pills li:not(.active)', toggleComparisonPanel);

Pointing to the function:

function toggleComparisonPanel() {
  event.preventDefault();
  $(this).addClass('active').siblings().removeClass('active');
  $quickSpecsTable.toggleClass('comparison-mode');    
  $filters.toggle();
}

This works in Chrome as apparently it attaches event to window making it global as I understand it. However Firefox requires the event to be passed to the function. I've tried this with no success:

$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();
}

Is something like this even possible, or is my only option to put the code into an anonymous function within the .on() function, something like the following code?

$comparePanel.on('click', '.pills li:not(.active)', function(event){
  event.preventDefault();
  $(this).addClass('active').siblings().removeClass('active');
  $quickSpecsTable.toggleClass('comparison-mode');    
  $filters.toggle();
});

I'd prefer to keep my event handler and the function separate if at all possible. Probably not much reason other than it feels tidier to me to be honest, but it'd be nice to do it

You can simply declare the function somewhere else, like this:

// 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);

there's an obvious syntax error (missing ")"). fixing it to

$comparePanel.on('click', '.pills li:not(.active)', toggleComparisonPanel(event));

would attach the result of toggleComparisonPanel(undefined) (assuming there's no event variable visible at this point).

you want to make it

$comparePanel.on('click', '.pills li:not(.active)', toggleComparisonPanel);

function toggleComparisonPanel(event) {
...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM