我编写了一个javascript函数,根据用户指定的行数和列数动态插入tr
和td
。我试图编写另一个函数,当我点击表格的特定单元格时,我会做某些事情。
这是生成表格的函数
$('#submit').on('click', function() {
numOfRow = $('#height').val();
numOfCol = $('#width').val();
const body = $('.grid-canvas');
for (var i = 1; i <= numOfRow; i++) {
let row = $('<tr id=\'' + i + '\'></tr>');
for (col = 1; col <= numOfCol; col++) {
row.append('<td id=\'' + col + '\'></td>');
}
body.append(row);
}
});
这是我动态生成的表格
<table class="table-bordered">
<tbody class="grid-canvas">
<tr id="1">
<td id="1"></td>
<td id="2"></td>
</tr>
</tbody>
</table>
分别尝试使用索引,但对我来说显而易见的是它不起作用。然而,这是我在单击单元格时执行某些操作的功能
let boxToFill = $('td').index();
$(boxToFill).click(function() {
console.log(boxToFill);
});
请问针对特定表格单元格的正确方法是什么?这是我使用javascript时的学习过程。
答案 0 :(得分:1)
我把一切都放在一个小例子中
function fillBox(element) {
// do something with element
element.style.backgroundColor = "red"
}
$(document).ready(() => {
$('#submit').on('click', function () {
numOfRow = 3;
numOfCol = 5;
const body = $('.grid-canvas');
for (var i = 1; i <= numOfRow; i++) {
let row = $('<tr id=\'' + i + '\'></tr>');
for (col = 1; col <= numOfCol; col++) {
row.append('<td onclick="fillBox(this)" id=\'r' + i + 'c' + + col + '\'>test</td>');
}
body.append(row);
}
});
});
&#13;
tr{
padding:20px;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="submit">create</button>
<table class="table-bordered">
<tbody class="grid-canvas">
</tbody>
</table>
&#13;
答案 1 :(得分:0)
我将.on('click')
绑定在表本身,只需使用特定的选择器,在您的情况下td
可能就足够了,因为click事件;见下面的例子:
$("#clickable_table").on('click', "td" ,function() {
console.log($(this).html()); // Just print the content for demo purposes
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table-bordered" id="clickable_table"> <!-- Added an ID -->
<tbody class="grid-canvas">
<tr id="1">
<td id="1">TD 1</td>
<td id="2">TD 2</td>
</tr>
</tbody>
</table>
答案 2 :(得分:-1)
// I tried to use the same way of doing that you did, 'index()' was a good idea…
// … but with my corrections. :)
let tds = $('td');
$(tds).click(function() {
console.log($(this).index()+' '+$(this).parent().index());
});
&#13;
/* Some CSS, to make it nicer */
.table-bordered{
border-collapse: collapse;
}
.table-bordered td {
border: 1px solid black;
padding: 2px 8px;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table-bordered">
<tbody class="grid-canvas">
<tr id="1">
<td>td1</td>
<td>td2</td>
</tr>
<tr id="2">
<td>td1</td>
<td>td2</td>
</tr>
</tbody>
</table>
&#13;
如果您想保留行号,也可以这样。