Moving forward, we will see how to attach event handlers
to dynamically inserted html contents.
As we know, it is very simple to handle an event for a
HTML control using jQuery. For example, the below jQuery code will attach an
onclick event which will alert the user with the value of html button user when
clicked.
<script src="scripts/jquery-1.4.2.min.js"
type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#clickMe").click(function() {
alert($(this).val());
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input type="button" id="clickMe" value="Click
ME"/>
At times, we will have requirements where we need to add
HTML controls/contents dynamically and handle the events raised by those dynamic
HTML controls. Consider the below code,
<script src="scripts/jquery-1.4.2.min.js"
type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#clickMe").click(function() {
$("#dvDynamic").append("<a
class=dynamiclink href=#>dynamic link</a><br>");
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input type="button" id="clickMe" value="Click
ME"/>
<div id="dvDynamic">
<b>Div Containing Dynamic
Links:</b><br />
</div>
</div>
</form>
</body>
</html>
The above code will add a hyperlink inside the div(id=
dvDynamic) whenever the button “Click Me” is clicked. Now, it is not possible to
handle the events for these dynamic hyperlinks like we normally do with jQuery
library.
Hence, the below code will not work for dynamic html
controls.
$("a.dynamiclink").click(function()
{
$("#dvDynamic").append("<a
class=dynamiclink href=#>dynamic link</a><br>");
});
To tackle this, jQuery team has introduced a new method
called live in jQuery version 1.3. You
can use this live method to attach an event handler for all elements which match
the current selector expression now and those getting added in future. Hence,
this method can be used to attach events for dynamic added html controls.
Using live method in jQuery to bind events
How to add or hookup events with dynamic html using
jQuery?
The below code snippet uses live method to hook up an
event with the dynamically inserted HTML content.
<script src="scripts/jquery-1.4.2.min.js"
type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#clickMe").click(function() {
$("#dvDynamic").append("<a
class=dynamiclink href=#>dynamic link</a><br>");
});
$("a.dynamiclink").live("click", function()
{
alert("Clicked dynamic link");
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input type="button" id="clickMe" value="Click
ME"/>
<div id="dvDynamic">
<b>Div Containing Dynamic
Links:</b><br />
</div>
</div>
</form>
</body>
</html>
When executed, the above code will alert with message
“Clicked dynamic link” whenever the dynamic hyperlink is clicked.
|