With jQuery, you can easily add dynamic html elements anywhere you want on the page. The problem is that the newly added elements will not binded to pre-defined events.This problem can be fixed by using "live". It allows you to define an event handler that will work with all matched elements either now or future.
Let us start with an example. I will create a div as a container and begin with a button that will let us create a dynamic "button" element inside the container. The newly created button will also binded to the same event that create more button inside the container when clicked.
Here is the code:
--
<html>
<head>
<script type='text/javascript' src='js/jquery.min.js'></script>
<script>
$(function(){
$('input:button').live('click', function(){
$('<input type="button" value="also add a button">').appendTo($('#container'));
});
});
</script>
</head>
<body>
<div id='container' style='border:solid black 2px; padding: 5px'>
</div>
<input type='button' value='add a button'>
</body>
</html>
--
If necessary, there is "die" that let you unbind the "live" events.
See jQuery API: live and jQuery API: die for more information.

No comments:
Post a Comment