How can I prevent the default event action when an event handler is attached to a parent HTML element?

advertisements

I have alot of links on my page that I want to be ajaxified so that when I click the link, it deletes the item, so I attached and event handler to a parent div like so:

<div id="parent">
   <a href='#' data-itemid='1'>Delete Me</a>
   <a href='#' data-itemid='2'>Delete Me</a>
   <a href='#' data-itemid='3'>Delete Me</a>
</div>

And I used the following JQuery

  $('#parent').delegate('a', 'ajax:beforeSend', function(event){
    event.preventDefault();
    var target = $(event.target);
    if (target.is('a')) {
      var itemid = target.attr('data-itemid');
      $.post("/item/"+itemid+'.json', {
        _method: 'delete'
      });
    }
  })
  .live('ajax:success', function(event, data, status, xhr){
    var itemid = data + '';
    console.log(itemid);
    $('item-' + itemid + '-content').fadeOut();
  });

The problem is that when I click the link, the POST gets submitted and my page receives the response, however the event.preventDefault() line does not seem to be working, because the click event goes through and sends a second GET request to reload my page.

How can I prevent this page reload from happening? I am using JQuery 1.5.1, and Rails 3.0.7.

Thanks


Just a guess, haven't tried it but try adding return false; to the end of the beforeSend anonymous function.

  $('#parent').delegate('a', 'ajax:beforeSend', function(event){
    event.preventDefault();
    var target = $(event.target);
    if (target.is('a')) {
      var itemid = target.attr('data-itemid');
      $.post("/item/"+itemid+'.json', {
        _method: 'delete'
      });
    }
    return false;
  })