2014-10-18 53 views
1

我有一個ajax塊正在處理來自外部API的json響應。我有一個名爲狀態的對象的字段,並根據狀態,我想顯示相應的工具提示。目前,我正在嘗試使用if語句來執行此操作,但是我收到錯誤消息。如果語句在ajax附加塊

的錯誤是:

​​

阿賈克斯阻止

<script type="text/javascript"> 
    $.ajax({ 
    url: "pull_overview", 
    dataType: "json", 
    cache: false, 
     success: function(data){ 
     if (data == null) { 
      $('#ajax-loader').hide() 
      $('#overviewlist tbody').append("<tr><td colspan='100'><h3><center>You have no recent transactions.</center></h3></td></tr>"); 
     } 
     else { 
      $('#ajax-loader').hide() 
      $.each(data, function(index, element) { 
      $('#overviewlist tbody').append("<tr><td>" + element.name + "</td><td>" 
                  + element.time + "</td><td>" 
                  + element.type + "</td><td>" 
                  + element.change_in_balance + "</td><td>" 
                  + element.method + "</td><td>" 
                  + 
                  if (element.status == 'New Transaction') { 
                  "<td><button type='button' class='tooltips btn-u btn-u-xs btn-u-purple' data-toggle='tooltip' data-placement='right' title='Your transaction is currently being processed'>Pending</button></td></tr>" 
                  } 
      }); 
     } 
    } 
    }); 
</script> 
+0

使用'(element.status =='New Transaction'?「...數據裏面如果...」:「」;)'而不是你if – 2014-10-18 16:39:31

回答

2

像錯誤說,你有一個的SyntaxError。固定代碼是:

$.ajax({ 
    url: "pull_overview", 
    dataType: "json", 
    cache: false, 
    success: function (data) { 
     if (data == null) { 
      $('#ajax-loader').hide() 
      $('#overviewlist tbody').append("<tr><td colspan='100'><h3><center>You have no recent transactions.</center></h3></td></tr>"); 
     } else { 
      $('#ajax-loader').hide() 
      $.each(data, function (index, element) { 
       $('#overviewlist tbody').append("<tr><td>" + element.name + "</td><td>" + element.time + "</td><td>" + element.type + "</td><td>" + element.change_in_balance + "</td><td>" + element.method + "</td><td>" + element.status == 'New Transaction' ? 
        "<td><button type='button' class='tooltips btn-u btn-u-xs btn-u-purple' data-toggle='tooltip' data-placement='right' title='Your transaction is currently being processed'>Pending</button></td></tr>" : ""); 
      }); 
     } 
    } 
}); 

什麼變化?

  • 一些缺少括號
  • 你不能有if語句的字符串(例如"foo" + if(something) "bar")內。改用三元運算符:"foo" + something ? "bar" : ""

有用的資源:

2

if語句你不能把一個字符串中的concatination的中間你最後的append電話。而不是

content = "<tr><td>" + element.name + "</td><td>" 
      + element.time + "</td><td>" 
      + element.type + "</td><td>" 
      + element.change_in_balance + "</td><td>" 
      + element.method + "</td><td>"; 
if (element.status == 'New Transaction') 
    content += "<td><button type='button' class='tooltips btn-u btn-u-xs btn-u-purple' data-toggle='tooltip' data-placement='right' title='Your transaction is currently being processed'>Pending</button></td></tr>"; 
$('#overviewlist tbody').append(content);