我设置了一个包含以下标题的表格。我设置代码设置为发送ajax请求以检索JSON数据,并在用户单击按钮时显示一个包含表格的对话框,然后我过滤此数据,以便它返回过滤后的数据(例如,Kevin)。以上所有都很好。现在我想将此数据(Kevin)插入相应的单元标题(例如Name)和其他数据(Number-> xxx-xxx-xxxx; address-> xxx ...等)。我想这样做,所以我确保将数据插入到正确的字段中。我需要在用户关闭对话框后清空该行。
使用Javascript:
executeAPI("GetUserInfo.php", "name", callback); // this returns Kevin
function exeCtCoreAPIcallback(result){
//need to append the result to the corresponding cell header here.
}
HTML:
<table id="data-table">
<thead>
<tr id="data-row" class="data-header">
<th>Name</th>
<th>Number</th>
<th>Address</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<tr>
</tr>
</tbody>
</table>
有没有办法引用<th>
的名称并在下面插入?
答案 0 :(得分:0)
这是我的解决方案:
<html>
<head>
<script
src="https://code.jquery.com/jquery-3.3.1.js"
integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="
crossorigin="anonymous"></script>
<script>
var myCellIndex=new Array();
$(document).ready(function()
{
//Initialize the name and index mapping
var th=$("#data-row > th");
for (var i=0;i<th.length;i++)
{
myCellIndex[th[i].innerHTML]=th[i].cellIndex;
}
});
function updateContent(fieldName,content)
{
var cellIndex=myCellIndex[fieldName];
var bodyRow=$("tbody>tr")[0]; // Because you have 1 row in tbody only.
if (bodyRow.cells.length<=cellIndex) //If the cell not found
{
for (var i=bodyRow.cells.length;i<=cellIndex;i++) //Add all necessary cells.
cell=bodyRow.insertCell(i);
}
else
cell=bodyRow.cells[cellIndex]; //Get a appropiate cell
cell.innerHTML=content; //Set the cell content.
}
function go()
{
var cell;
updateContent("Name","Kevin");
updateContent("Number","xxx-xxx-xxxx");
updateContent("Status","bla bla");
updateContent("Address","xxx...");
}
</script>
</head>
<body>
<table id="data-table">
<thead>
<tr id="data-row" class="data-header">
<th>Name</th>
<th>Number</th>
<th>Address</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<tr>
</tr>
</tbody>
</table>
<input type="button" value="Go" onclick="go()">
</body>
</html>