我的网站上有一个 html 表格,显示实时数据。我正在使用 PHP、MySQL 和 AJAX 的组合来检索它。
随着检索到新数据,表格行被添加到表格中。一切都按预期工作。
我想在 <td>
中添加一个字形图标取决于 javascript 变量的内容。
我的html表格如下;
<table id="transactionTable">
<thead>
<tr>
<th>ID</th>
<th>Date / Time</th>
<th>Card No</th>
<th>Direction</th>
</tr>
</thead>
</table>
向表中添加行的 jquery;
$("#transactionTable").prepend('<tr><td>'+data.SerialNo+'</td><td>'+dateFormatted+'</td><td>'+data.CardNo+'</td><td id="direction">'+data.Direction+'</td></tr>');
我想做的是,
// data.Direction is coming from the server
if(data.Direction == 'I') {
// add <span class="glyphicon glyphicon-import"></span>
}
if(data.Direction == 'O') {
// <span class="glyphicon glyphicon-export"></span>
}
所以表格行应该是这样的;
// if(data.Direction == 'I')
<tr>
<td>1</td>
<td>News</td>
<td>News Cate</td>
<td><span class="glyphicon glyphicon-import"></span> In</td>
</tr>
或者;
// if(data.Direction == 'O')
<tr>
<td>1</td>
<td>News</td>
<td>News Cate</td>
<td><span class="glyphicon glyphicon-export"></span> In</td>
</tr>
如有任何建议,我们将不胜感激。
最佳答案
确定要显示的图标,将其存储在变量中并将其添加到要传递给前置方法的字符串中。
var iconHtml = '';
if (data.Direction == 'I') {
iconHtml = '<span class="glyphicon glyphicon-import"></span> ';
}
if (data.Direction === 'O') {
iconHtml = '<span class="glyphicon glyphicon-export"></span> ';
}
$("#transactionTable").prepend('<tr><td>' + data.SerialNo +'</td><td>'+dateFormatted+'</td><td>'+data.CardNo+'</td><td id="direction">' + iconHtml +data.Direction+'</td></tr>');
```
关于javascript - 将 Glyphicon 动态添加到表格行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45738531/