var button = document.getElementById('btn'),
table = document.getElementById('tableBody');
button.addEventListener('click', function() {
var row = table.insertRow();
for (var c = 0; c < 4; c += 1) {
row.insertCell(c).innerHTML = "cell";
}
});
&#13;
<html>
<body>
<table border="1">
<thead>
<th>Column 1</th>
<th>Column 2</th>
<th>Column 3</th>
<th>Column 4</th>
<th>
<button id="btn">Insert</button>
</th>
</thead>
<tbody id="tableBody">
</tbody>
</table>
</body>
</html>
&#13;
如何点击动态添加的行并获取我使用普通JS或jQuery单击的单元格的索引
答案 0 :(得分:0)
如果您不想标记单元格(例如,如果您还要以任何顺序删除它们),那么执行此操作的一种方法是获取单击目标元素,找到它的parentNode然后检查每个单元格查看它是否是您单击的目标。所以你会说:
定义一个这样的函数:
function getCellIndexFromClick(event) {
var i, cell = event.target, nodes = cell.parentNode.childNodes;
for (i=0; i<nodes.length; i++) {
if (nodes[i] === cell) {
return i; //or do something else with i, or whatever.
}
}
}
然后在你的代码中添加:
cell.addEventListener("click", getCellIndexFromClick);
免责声明:我实际上没有尝试过,我只是在这里直接打字。
答案 1 :(得分:0)
var button = document.getElementById('btn'),
table = document.getElementById('tableBody');
button.addEventListener('click', function() {
var row = table.insertRow();
for (var c = 0; c < 4; c += 1) {
row.insertCell(c).innerHTML = "cell";
}
});
$("body").on("click", "td", function(){
var column_num = parseInt( $(this).index() ) + 1;
var row_num = parseInt( $(this).parent().index() )+1;
alert( "Row_num =" + row_num + " , Rolumn_num ="+ column_num );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<body>
<table border="1">
<thead>
<th>Column 1</th>
<th>Column 2</th>
<th>Column 3</th>
<th>Column 4</th>
<th>
<button id="btn">Insert</button>
</th>
</thead>
<tbody id="tableBody">
</tbody>
</table>
</body>
</html>