1
我正在经历一个问题,我正在使用jQuery创建一个html表格并将click事件添加到其表格单元格中。它工作得很好,但是当我在表中添加一个新的表格行时,它不会捕获新创建的行上的点击事件。耳机行工作正常。无法通过jquery获取新创建的表格单元格
我发送你我的代码你的帮助将受到高度赞赏。
<%@页面语言= “C#” AutoEventWireup = “真” 的CodeFile = “Default.aspx.cs” 继承= “_默认” %>
<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++) {
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>
感谢名单了很多,但有点困惑的是,为什么我需要为新创建的单元格添加委托时,前面的细胞,而不设置委托即使工作? – 2010-11-20 10:10:30
@Abdul你不这样做,你应该使用这个*代替点击事件处理程序 - 这也适用于你现有的单元格。如果你想详细解释'delegate'和'bind'之间的区别,你可以看看我在答案中链接到的文档,或者搜索那些比我更有经验的人提供的优秀解释在这里 – 2010-11-20 10:13:28