The jQuery code doesn't work when running normally. But I do with breakpoints included

I have the following code in my application:

$(".deleteproduct").click(function() {
    id = this.id;
    alert("id: " + id);
});

      

If I run my site, nothing happens when I click on the element with the removeeproduct class. But when I set breakpoints before lines 1,2 and 3, it works like a charm.

Items with the removeeproduct class are loaded via an AJAX call right behind $ (document) .ready (function (). The .click code is below it.

This seems very strange to me. It works if breakpoints are used in Firebug, but not when they are not ...

+2


a source to share


3 answers


If you are loading an element .deleteproduct

via Ajax, you may need to define a click function using the jQuery live event handler.

$(".deleteproduct").live('click', function(){
    id = this.id;
    alert("id: "+id);
});

      



or put the function above in the Ajax callback.

+5


a source


I like the race condition. Do you remember that this code is inside

$().ready(function(){
    ....
});

      



This means that the document is fully loaded before you try to execute the script in the DOM.

0


a source


$(document).ready(function(){
    $(".deleteproduct").click(function(){
        var id = $(this).attr('id');
        alert("id: "+id);
    });
});

      

0


a source







All Articles