javascript - 将 Glyphicon 动态添加到表格行

标签 javascript jquery html glyphicons

我的网站上有一个 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/

相关文章:

javascript - 具有流畅语法和光滑 js 的水平时间线

javascript - 使用托管字段时如何处理现有客户付款方式?

javascript - 使用默认的 .sort() 对 JavaScript 中所需的数组对象进行排序

jquery - 动态创建的字段

html - www.xyz.com 和 xyz.com 之间的区别以及如何重定向 .htaccess

javascript - 将值从一个 iframe 发布到另一个 iframe

php - 显示自定义帖子类型标题的列表

javascript - 根据用户帐户隐藏菜单项

javascript - 无法获取多个 Canvas 饼图

jquery - JW Player不重复播放视频