2012-07-02 55 views
0

下午, 我想知道如何根據從Web服務返回的值添加類。如果返回值爲真,請在AJAX中添加一個類

$.each(result, function (index, res) { 
      new_record = "<tr>" + 
         "<th scope=\"row\" class=\"t-left\"><a href=\"editproduct.aspx?sku=" + res.sku + "\" title=\"Edit this product listing\">" + res.title + "</a></th>" + 
         "<td><a href=\"http://www.amazon.co.uk/dp/" + res.asin + "\" target=\"_blank\" title=\"Visit the Amazon product listing\" >" + res.asin + "</a></td>" + 
         "<td>" + res.sku + "</td>" + 
         "<td>" + res.stock + "</td>" + 
         "<td> £" + res.price + "</td>" + 
         "<td>" + res.live + "</td>" + 
         "</tr>"; 

      $('#dataResults').append(new_record); 

我也返回一個值stockUpdated,我想補充一個類來改變取決於庫存表字段的顏色,如果這回來真的。

我不記得我怎麼以前這樣做,但如果聲明其類似於

許多在此先感謝。

艾倫

+0

該位...「​​」+ res.stock +「」+ – thatuxguy

+0

本質上「「+ – thatuxguy

+0

剛纔意識到這一點,並刪除了之前,我看到你的評論 – bfavaretto

回答

2

假設我理解正確你的問題,你可以在類屬性只是添加到字符串取決於你stockUpdated財產是否計算結果爲真還是假:

$.each(result, function (index, res) { 
    new_record = "<tr>" + 
       "<th scope=\"row\" class=\"t-left\"><a href=\"editproduct.aspx?sku=" + res.sku + "\" title=\"Edit this product listing\">" + res.title + "</a></th>" + 
       "<td><a href=\"http://www.amazon.co.uk/dp/" + res.asin + "\" target=\"_blank\" title=\"Visit the Amazon product listing\" >" + res.asin + "</a></td>" + 
       "<td>" + res.sku + "</td>" + 
       "<td" + (res.stockUpdated ? " class='updated'" : "") + ">" + res.stock + "</td>" + 
       "<td> £" + res.price + "</td>" + 
       "<td>" + res.live + "</td>" + 
       "</tr>"; 

    $('#dataResults').append(new_record); 
}); 

我因爲我喜歡將字符串連接在一起,所以它已經完成了第三級條件的內聯。您可以輕鬆地停止前一個td結尾處的級聯,然後在下一個td周圍包含完整的if聲明。

+0

完美謝謝: )現在我明白了,我記得它!將盡快標記爲答案:) – thatuxguy

+0

@thatuxguy - 不客氣,很高興我可以幫助:) –

0

您可以創建一個變量,並與類屬性來填充它:

var classAttr = (res.StockUpdated) ? "class=\"updated\"" : ""; 

然後,你可以只是做:

"<td " + classAttr + ">" + res.stock + "</td>" + 

完整的示例:

$.each(result, function (index, res) { 
     var classAttr = (res.StockUpdated) ? "class=\"updated\"" : ""; 
     new_record = "<tr>" + 
        "<th scope=\"row\" class=\"t-left\"><a href=\"editproduct.aspx?sku=" + res.sku + "\" title=\"Edit this product listing\">" + res.title + "</a></th>" + 
        "<td><a href=\"http://www.amazon.co.uk/dp/" + res.asin + "\" target=\"_blank\" title=\"Visit the Amazon product listing\" >" + res.asin + "</a></td>" + 
        "<td>" + res.sku + "</td>" + 
        "<td " + classAttr + ">" + res.stock + "</td>" + 
        "<td> £" + res.price + "</td>" + 
        "<td>" + res.live + "</td>" + 
        "</tr>"; 

     $('#dataResults').append(new_record); 
+0

'class'是JavaScript中的保留字。您必須另外調用該變量。 –

+0

好的,謝謝! –

相關問題