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 button is clicked in midiv welcome.html is loaded and button gets hidden.
welcome.html is 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’s onClick is not working. Why?
Simple solution here – you’ll need to use the jQuery
.live()function to add an event handler for the new button.When you initially created the
.click()handler, that secondbuttonwas not yet in the DOM, so jQuery could not attach an event handler to it. The.live()function will work for any element that is already in the DOM and also any element that will be added in the future (e.g. from an ajax call).You might want to give your new button (from the ajax call) a new and different ID as the selector
$("button")will capture both your buttons (even though one is hidden).NOTE!
Since version 1.7 of jQuery, the
live()method has been deprecated!. As of version 1.9 this function will be removed completely… The correct way to deal with event handlers of these dynamically added elements is now to use theon()function.