Jquery click does not work with ajax generated content

I use $(".button").on("click", function(){ });

to click on the button that is in the container, but then the ajax call is made and the contents are updated with new material, and then when I try to click .button it will not work ... nothing will work when I press the button.

I even tried

 $(".button").live("click", function(){ }); 

or

 $(".button").click(function(){ }); 

How can I make it work?

EDIT: my html:

 <div class="container"> <ul> <li>item1</li> <li>item2</li> <li>item3</li> </ul> <input type="button" value="reload" class="button" /> </div> 
+56
jquery ajax click live
Feb 18 2018-12-18T00:
source share
4 answers

Should be done that way.

 $('body').on('click', '.button', function (){ alert('click!'); }); 

If you have a container that does not change during ajax request, this is more efficient:

 $('.container').on('click', '.button', function (){ alert('click!'); }); 

Always associate a delegate event with the nearest static element that will contain dynamic elements.

+120
Feb 18 2018-12-18T00:
source share

Ok, I solved my problem using the .on () function correctly, since I was missing one parameter.

instead

 $(".button").on("click", function() { } ); 

I used

 $(".container").on("click", ".button", function() { } ); 
+37
Feb 18 2018-12-18T00:
source share

Instead:

 $(".button").on("click", function() { } ); 

I used:

 $(".container").on("click", ".button", function() { } ); 

I used this and it worked.

+8
Apr 03 '13 at
source share

Is this what you are trying to do? Notice I put $.on() in the parent, but choose .button for the action.

.on (events [, selector] [, data], handler (eventObject))

selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event always fires when it reaches the selected item.

http://api.jquery.com/on/

 <div id="stuff"> <button class="button">Click me!</button> <p>Stuff</p> </div> var $stuff = $('#stuff'), ajaxContent = $stuff.html(); $stuff.on('click', '.button', function(){ $.get('/echo/html/', function(){ $stuff.empty(); console.log($stuff.html()); alert($stuff.html()); // Look behind, #stuff is empty. $stuff.html(ajaxContent); console.log($stuff.html()); }); }); 

http://jsfiddle.net/62uSU/1

Another demo:

 var $stuff = $('#stuff'), ajaxContent = $stuff.html(), $ajaxContent, colors = ['blue','green','red'], color = 0; $stuff.on('click', '.button', function(){ $.get('/echo/html/', function(){ color++; if (color == colors.length) color = 0; console.log($stuff.html()); alert($stuff.html()); $ajaxContent = $(ajaxContent); $stuff.append($ajaxContent).css('color', colors[color]); console.log($stuff.html()); }); }); 

http://jsfiddle.net/62uSU/2/

+3
Feb 18 2018-12-18T00:
source share



All Articles