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