There are two methods in jquery that can be used to bind automatically appended DOM objects. They are live and delegate. In fact, these two methods are a variant of the bind method. When dealing with fixed DOM objects, we usually use Just bind is enough, but for DOM objects dynamically generated by objects, there is nothing you can do using bind. At this time, live and delegate come into play, haha.
The live method is used to bind a certain object (of a certain type) and bind methods to them.
Copy the code code as follows:
//live
$("td").live("click", function () {
alert($(this).html());
});
//The following is also possible$("#list td").live("click", function () {
alert($(this).html());
});
The delegate method is used to bind sub-objects under a certain (certain type) object and bind methods to the sub-object (delegate the sub-object so that the sub-object has a certain method, haha)
Copy the code code as follows:
$("#list").delegate("td", "click", function () {
alert($(this).html());
});
The completed code of the DEMO below:
Copy the code code as follows:
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
<script src="jquery.js" type="text/javascript"></script>
<script id="listTemplate" type="text/html">
<tr>
<td>[UserID]</td>
<td>[UserImg]</td>
<td>[UserName]</td>
</tr>
</script>
<script type="text/javascript">
var reg = new RegExp("//[([^//[//]]*?)//]", 'igm'); //igm refers to specifying case-sensitive matching and global matching respectively Matches multiple lines.
$(function () {
//live
$("#list td").live("click", function () {
alert($(this).html());
});
$("#addFun").click(function () {
var html = document.getElementById("listTemplate").innerHTML;
var source = html.replace(reg, function (node, key) { return { 'UserImg': '1', 'UserName': 'zhang', 'UserID': '1' }[key]; });
$("#list").append(source);
});
});
</script>
</head>
<body>
<div id="comment_ul_2">
</div>
<input type="button" id="addFun" value="click me" />
<table id="list">
<tbody>
</tbody>
</table>
</body>
</html>