Unable to get the newly created table cell through jquery
I am going through a problem that i am creating a html table using jquery and add click event to its table cells. it is working perfectly fine but when i add a new table row in that table then it wont catch the click event on the newly created row. The earler rows are working fine.
I am send u my code your help will be highly appreciated.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<style type="text/css">
.cpHeader
{
color: white;
background-color: #719DDB;
font: bold 11px auto "Trebuchet MS", Verdana;
font-size: 12px;
cursor: pointer;
width:450px;
height:18px;
padding: 4px;
}
.cpBody
{
background-color: #DCE4F9;
font: normal 11px auto Verdana, Arial;
border: 1px gray;
width:450px;
padding: 4px;
padding-top: 7px;
}
.imageClass
{
background-image:url(Images/expand.png);
}
.tableCell
{
padding: 5px;
}
.buttonCSS
{
width:50px;
height:50px;
background-color:Green;
}
</style>
<script type="text/javascript">
$(document).ready(function () {
createTable($("#tbl"), 5, 5);
$(".tableCell").click(function () {
alert("Column # = " + $(this).data("col") + "\n Row # = " + $(this).data("row"));
});
function createTable(tbody, rows, column) {
if (tbody == null || tbody.length < 1) {
return;
}
for (var i = 0; i < rows; i++) {
var trow = $("<tr>");
trow.data("trow", i);
for (var j = 0; j < column; j++) {
var celltext = "" + i + "." + j;
$("<td>")
.addClass("tableCell")
.text(celltext)
.data("col", j + 1)
.data("row", i + 1)
.appendTo(trow);
}
trow.appendTo(tbody);
}
$(tbody).data("rows", rows);
$(tbody).data("cols", column);
}
$("#addRowBtn").click(function () {
var table = $("#tbl");
var trow = $("<tr>");
var columns = table.data("cols");
for (var i = 0; i < columns; i++) 开发者_如何学C{
var td = $("<td>")
td.addClass("tableCell");
td.data("col", i + 1)
td.data("row", table.data("rows") + 1 )
td.text("" + (table.data("rows") + 1) + "." + (i + 1))
td.appendTo(trow);
}
trow.appendTo(table);
table.data("rows", table.data("rows") + 1);
});
});
</script>
You should be using the delegate
function to bind your event handlers here.
$('#tbl').delegate('.tableCell', 'click', function(){
alert("Column # = " + $(this).data("col") + "\n Row # = " + $(this).data("row"));
});
This will catch all clicks on .tableCell
s that are children of #tbl
, even if the .tableCell
elements do not exist at the time which delegate
is called.
Here's a simple demo demonstrating this live: http://www.jsfiddle.net/yijiang/hBkKh/
精彩评论