Why does 'return false' not prevent page reload on onclick

时间:2015-09-14 15:52:06

标签: javascript jquery ajax

I already tried this code but it does not prevent page reload on onclick function. What should I do? Did I miss something or is this a browser compatibility issue?

function track_specs() {
  $('button[name="delete_spec"]').each(function() { 
    this.onclick = null; 
    $(this).click(function () { 
      delete_specs($(this).data("id")); 
      return false; 
    }); 
  });
}

2 个答案:

答案 0 :(得分:3)

Instead of the code, can you try this? You don't need to loop through all the <button> tags which is a costly one. You can use this:

$(document).ready(function () {
  $('button[name="delete_spec"]').click(function (e) {
    e.preventDefault();
    delete_specs($(this).data("id")); 
  });
});

答案 1 :(得分:1)

A <button> shouldn't initiate a page reload on click unless you have another click listener that reloads the page or maybe in your delete_specs function.

You could try this:

$(this).click(function(e) {
  e.preventDefault();
  ...
});

But I think you are explicitly reloading the page somewhere else (through window.location = ...).