我的HTML:
<html>
<head>
<title>Table</title>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
<script type="text/javascript" src="script.js"></script>
</head>
<body>
Row:<input id="gRow">Col:<input id="gCol"><button onClick="selectCell()">Find</button>
<button onClick="addCol(); update();">Add Col</button><br/>
<button onClick="addRow(); update();">Add Row</button><br/>
<table id="tab">
<tr class="rowtitle">
<td></td>
<th>1</th>
</tr>
<tr class="row row-1">
<th class="coltitle">1</th>
<td class="col col-1 edit"></td>
</tr>
</table>
<script type="text/javascript">
update();
function update(){
$('.edit').bind('dblclick', function() {
$(this).attr('contentEditable', true);
}).blur(function() {
$(this).attr('contentEditable', false);
});
}
</script>
</body>
</html>
我的Javascript:
nCol = 1,
nRow = 1;
var addCol = function(){
nCol++;
//add nes cols
$('.rowtitle').append("<th class='title'>"+nCol+"</th>");
for (var i = 0; i <= nCol; i++) {
$('.row-'+i).append( "<td class = 'col col-" + i + " edit'></tr>" );
};
};
var addRow = function(){
nRow++;
$("#tab").append( "<tr class = 'row row-" + nRow + "'></tr>" );
$('.row-'+nRow).append("<th class='coltitle'>"+nRow+"</th>")
//add nes cols
for (var i = 1; i <= nCol; i++) {
$('.row-'+nRow).append( "<td class = 'col col-" + i + " edit'></tr>" );
};
};
var selectCell = function(){
var col = $('#gCol').val(),
row = $('#gRow').val();
console.log('.row-'+row+' .col-'+col);
$('.row-'+row+' .col-'+col).css('background-color', 'red');
};
当我使用selectCell时,我发现它无效。经过检查,我注意到这些行正在做他们应该做的事情,每次都是一个独特的课程。但是,列会在一行中重复多次。我该如何解决这个问题?
要查看实际发生的情况,请创建一堆行和列。然后键入第3行和第5列。这是应该发生的事情。但是,现在输入1和1。 Demo
答案 0 :(得分:2)
你的addCol被窃听了。它应该是:
var addCol = function () {
nCol++;
//add nes cols
$('.rowtitle').append("<th class='title'>" + nCol + "</th>");
$('.row').append("<td class = 'col col-" + nCol + " edit'></tr>");
};