将 Glyphicon 动态添加到 Table 行

Add Glyphicon to Table Row Dynamically

我的网站上有一个 html table 显示实时数据。我正在使用 PHP、MySQL 和 AJAX.

的组合来检索它

Table 行被添加到 table 中作为检索新数据。一切都按预期工作。

我想根据 javascript 变量的内容向 <td> 添加一个字形。

我的htmltable如下;

<table id="transactionTable">
    <thead>
        <tr>
            <th>ID</th>
            <th>Date / Time</th>
            <th>Card No</th>
            <th>Direction</th>
        </tr>
    </thead>
</table>

向 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>
}

所以 table 行应该是这样的;

// 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>');

```

这是其中一种方法:我们正在创建一个变量,该变量将根据方向设置为正确的图标 class。

var directionIcon;

// Decide which icon class should be used depending on the data.Direction
if(data.Direction == 'I') directionIcon = 'glyphicon-import';
else if(data.Direction == 'O') directionIcon = 'glyphicon-export';

现在我们有了图标的 class 名称,我们可以创建 span 元素了。

// Create the span using the correct icon
directionIcon = '<span class="glyphicon ' + directionIcon + '"></span>';

基本上就是这样。现在我们需要做的就是在创建行时使用它。

// Create table row, including the icon before direction
$("#transactionTable").prepend('<tr><td>'+data.SerialNo+'</td><td>'+dateFormatted+'</td><td>'+data.CardNo+'</td><td id="direction">'+ directionIcon + ' ' + data.Direction+'</td></tr>');

data.Direction 是否始终存在,它是否始终等于 IO?如果是这样,这是其他答案的稍微浓缩的版本:

var iconSuffix = data.Direction == "I" ? "import" : "export";
$("#transactionTable").prepend('<tr><td>'+data.SerialNo+'</td><td>'+data.dateFormatted+'</td><td>'+data.CardNo+'</td><td id="direction"><span class="glyphicon glyphicon-'+iconSuffix+'"></span>'+data.Direction+'</td></tr>');