这看起来很简单,但我就是无法理解它。我正在尝试插入返回的数据并替换指定单元格索引处的单元格内容。我正在从函数调用的输入参数中获取数据 (Kevin
) 和索引 (0
)。但我无法将这些数据插入到所需的单元格中。我试过 insertCell
函数,但这不会替换内容,它只会继续添加新的单元格。
我的 console.logs 报告了正确的索引和数据,我试过像这样插入/替换单元格的内容:td[index].innerHTML = data
但这会出错,显然 td[index]
返回一个 object HTMLTableCellElement
,所以我不能这样做。
HTML:
<table>
...
<tbody>
<tr id="data-row-body">
<td></td> //need to insert here
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
Javascript:
function exeAPI(api, key, index, callback) {
$.ajax({
url:"../lib/getData.php",
type: "POST",
data: {
name: name,
api: api
},
dataType: "text",
success:function(result){
console.log(result);
if(result){
try {
var jsonText = result.substr(result.indexOf('{'));
console.log("this is the jsontext: " + jsonText);
var jsonObj = JSON.parse(jsonText);
callback(jsonObj.response.result[key], index);
} catch(e) {
console.log(e);
alert("Error getting rack data!");
}
}
}
});
//getting back "Kevin" and "0" as parameters to insert here
function exeAPIcallback(data, index){
var td = $('#data-table tbody td');
var tr = $('#data-table tbody tr');
var row = document.getElementById("data-row-body");
console.log("This is the cell index: " + th[index].innerHTML + " ,index: " + th[index]);
console.log("This is the cell index: " + td[index]);
td[index].innerHTML = data; // this doesn't work
}
function popupParamChecker(){
exeAPI("getData.php", "Kevin", 0, exeAPIcallback);
$("#dialog-params").dialog({
resizable: false,
width: 1000,
modal: true,
draggable: false,
buttons: {
Confirm: function() {
$( this ).dialog( "close" );
}
}
});
}
有更简单的方法吗?
最佳答案
行数可能很多,所以我为你的 APICallback 添加了一个参数。
下面是代码:
1.首先通过$('table tbody tr')
2.使用.eq(index)
获取特定行
3. .find()
所有 tds 然后获取特定单元格以更改文本。
function exeAPIcallback1(data, row, col){
let td = $('table tbody tr').eq(row).find('td').eq(col);
td.text(td.text()+data)
}
function exeAPIcallback2(data, row, col){
$('table tbody tr').eq(row).find('td').eq(col).text(data);
}
table td{
width:10px;
height:10px;
border:1px;
background-color:yellow;
}
table td:nth-child(even){
background-color:red
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button onclick="exeAPIcallback1('test',0,0)"> Test Insert</button>
<button onclick="exeAPIcallback2('test',0,0)"> Test Replace</button>
<table>
<tbody>
<tr id="data-row-body">
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
关于Javascript使用索引和数据将数据插入单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49459545/