简体   繁体   中英

Javascript on click event not working within a function but works in document.ready()

Inside my document.ready(), I have a few buttons (a, b, c) and when clicked they call a specific method. However, when I click on button (d), I need buttons (a,b,c) to stop calling their specific methods and do nothing when clicked. I tried using the preventDefault() method, but it did not work. Someone please help! Thanks in advance :)

$(document).ready(function(){ 
  ...

  // my buttons (a,b,c) which call method fA
  $("#a, #b, #c").on("click", fA);

  // my button (d) which call method fB
  $('#d').on("click", fB);

  ...
});

// When button (d) is clicked, I want buttons a,b,c to be non-clickable and this method should not be called.
function fA() { 
  // does a AJAX request
  $.ajax({
    url: ...,
    data: ...,
    dataType: "script"
  });
}

function fB() {
  $("#a, #b, #c").on("click", function(e) {
    e.preventDefault(); // THIS IS NOT WORKING!
  });
  ... 
  //Does its own unique AJAX request
}

When you call .on() , event handlers are not replaced — they're added . Any element may have many event handlers for the same event. You're successfully adding new "click" handlers, but the old ones are still there too.

You can use .off() to remove all handlers for a particular event.

$('#a, #b, #c').off("click");

If you want some existing handlers to be temporarily disabled, you can either set the "disabled" property directly on the elements involved (provided they're the right kinds of elements), or else use some flagging mechanism of your own.

As an example of "flagging" to know when the handlers should/shouldn't operate, you can use a class:

function fA() { 
  if ($(this).hasClass('inactive')) return;

  // does a AJAX request
  $.ajax({
    url: ...,
    data: ...,
    dataType: "script"
  });
}

function fB() {
  $("#a, #b, #c").addClass('inactive');
  // ...

When you want the "A" function to start working again, you can just remove that class:

$('#a, #b, #c').removeClass('inactive');

Change function fB to:

function fB() {
  $("#a, #b, #c").off("click");
  ... 
  //Does its own unique AJAX request
}

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