Question

$.each(data, function(i,data) {
...[cut]...
    +"<a id=\"contact_"+data.id+"_delete\" href=\"/user/contact/delete/ticket_id/"+data.ticket_id+"/contact_id/"+data.id+"\">Delete</a>"
...[cut]...
    $("#contact_"+data.id+"_delete").live('click',function() {
        var href = this.attr('href');
        alert(href);
        return false;
    });

I have the following code sample (irrelevant parts cut out for simplicity). What I have is a function that redraws the rows (tr's) of a table. Each row has a 'delete' link at the end of the row that calls a url /user/contact/delete/ticket_id/{$ticket_id}

Then (within the same loop), I want to bind a click event to the newly created link. However when I click the link, the browser leaves the page and goes to the url rather than going to the clicked link function.

First, am I binding the click event properly?

Second, am I retrieving the 'href' attribute of the element correctly?

Was it helpful?

Solution

In addition to what @charlietfl says, you could have a single handler for all of your delete elements. Simply add the same class to all of them, like class="contact_delete", and then use .on() to target all of them:

+'<a class="contact_delete" id="contact_'+data.id+'_delete" ...

Note that if you use single quotes, you don't have to escape all of your double-quotes.

$('body').on('click', '.contact_delete', function() {
    var href = $(this).attr('href');
    alert(href);
    return false;
});

OTHER TIPS

You need to wrap "this" in $() to make it a jQuery object in order to use jQuery methods

 var href = $(this).attr('href');

live() is deprecated ( but working in 1.7.1) so you should consider using more current on() method

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top