2017-08-17 135 views
2

我的網站上有一個html表格,顯示數據的實時動態。我正在使用PHP,MySQL和AJAX的組合來檢索它。添加Glyphicon動態表格行

隨着新數據的檢索,表格行被添加到表格中。一切都按預期工作。

我想添加一個glyphicon到<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> 

任何意見表示讚賞。

回答

1

確定要顯示哪個圖標,將其存儲在一個變量中,並將其添加到要傳入prepend方法的字符串中。

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

```

+0

完美的作品!謝謝 – TheOrdinaryGeek

0

這是這樣做的一個:我們要創建將被設置爲正確的圖標類,根據方向的變量。

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

現在我們有了圖標的類名,我們可以創建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>'); 
0

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