【发布时间】:2018-09-02 17:08:07
【问题描述】:
这看起来很简单,但我就是想不通。我正在尝试插入返回的数据并替换指定单元格索引处的单元格内容。我从函数调用的输入参数中获取数据 (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" );
}
}
});
}
有没有更简单的方法?
【问题讨论】:
-
我返回的是
data,即Kevin。 -
我已经做了,它不是一个空字符串。当我这样做
var tr = $('<tr>'); $('<td>').html(data).appendTo(tr); tbody.append(tr)时,我在第一个索引中看到了正确的值。当我使用追加以这种方式执行此操作并从 html 中删除<td>和<tr>时,它可以工作。但我需要一种方法来使用我想要的索引值,而且我不能继续追加,它需要替换当前的单元格索引。 -
$('<td>').html(data)非常危险,它可能会破坏一些东西。 -
@Sphinx 是的,但为什么它适用于
append,而不适用于您建议的解决方案?对话框创建时数据还没有准备好? -
这样就可以了。
标签: javascript jquery html html-table cells