JQuery function does not work with loaded AJAX content

I have a page index.html:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    <title>Lufia</title>
    <script src="js/jquery.js" language="javascript"></script>
    <script language="javascript">

    $(document).ready(function() {
      $("button").click(function() {
        $('#mydiv').html( 'Loading... ').load('welcome.html');
        $(this).hide();
      });
    });

    </script>
  </head>
  <body>
    <button>ajax</button><div id="mydiv"></div>
  </body>
</html>

In this code, when the button is pressed in midiv welcome.html, it loads and the button hides.

welcome.html as follows:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    <title>Lufia</title>
  </head>
  <body>
    <button>New Button</button>
  </body>
</html>

This new button onClickdoes not work. Why?

+3
source share
5 answers

The simple solution is here - you need to use the jQuery function .live()to add an event handler for the new button.

$("#newButton").live('click',function(){
  // Do stuff here
});

.click(), button DOM, jQuery . .live() , DOM, , (, ajax).

, ( ajax) , $("button") ( ).


!

1.7 jQuery, live() !. 1.9 ... on().

+12

Live . .

$(document).on("click", "button", function() {

- / .

http://api.jquery.com/live/

+3

.

, welcome.html .

; onclick , ajax.done() .

- - : . .

<script language="javascript">
$(document).ready(function(){

var buttonClickEvent = function(){
  $.ajax({
     url: "test.html",
  }).done(function(results) { 
    $('#mydiv').html(results);
    $('button').live('click',buttonClickEvent);
  });
}

$("button").click(buttonClickEvent);

</script>

:

welcome.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
 <title>Lufia</title>

<body><button>New Button</button>

<script>
 $(document).ready(function(){
    $("button").click(function(){
       //do something
    });
 });
</script>

+2

, jquery . , , .....

0

- .

jquery.hotkeys-0.7.9.min.js .

2 , . ,

:)

-1

All Articles