2017-08-02 22 views
1

試圖顯示:Name |行業|當前價格到HTML表格。無法使用jQuery訪問數組並在表上顯示

請查看我的代碼並幫助我在HTML頁面上顯示數據。

我錯過了什麼不能在HTML上顯示? 我的訪問數組的方式錯了嗎?

這是我test.js腳本

$(document).ready(function() { 
 

 
     var test_data = [ 
 
          { 
 
           "current_price": 1626.0, 
 
           "name": "HDFC Bank", 
 
           "industry": "Financials", 
 
           
 
          }, 
 
          { 
 
           "current_price": 7064.8, 
 
           "name": "Maruti Suzuki", 
 
           "industry": "Automobiles", 
 
          } 
 
         ]; 
 

 
     $.each(data, function(key, val) { 
 
     test_data += '<tr>' ; 
 
     test_data += '<td>'+val.name+"<td>" ; 
 
     test_data += '<td>'+val.industry+"<td>" ; 
 
     test_data += '<td>'+val.current_price+"<td>" ; 
 
     s_data += '</tr>' ; 
 

 
     }); 
 

 
     $('#test').appendTo(test_data); 
 

 
}); 
 

 

 

 

 
Below is my **HTML Page** :
<html> 
 
<head> 
 
Test 
 
    
 
</head> 
 
<body> 
 
<table class="table table-hover" id="test"> 
 
    <thead> 
 
    <tr> 
 
     <th>Company Name</th> 
 
     <th>Industry </th> 
 
     <th>Current price</th> 
 
    </tr> 
 
    </thead> 
 
    <tbody> 
 

 
    </tbody> 
 
</table> 
 

 
<script src="js/jquery-3.2.1.min.js"></script> 
 
<script src="js/bootstrap.min.js"></script> 
 
<script src="js/test.js"></script> 
 
</body> 
 
</html>

回答

0

有許多與代碼的問題。大部分都是用名字。例如,test_data是數據的數組,但test_data是html的構建地!然後jQuery循環遍歷數據(而不是test_data)。那麼什麼是s_data?一個錯字!然後關閉TD缺失,然後test_data應附加到表,而不是相反。

這裏是工作的代碼(and here is the JsFiddle):

$(document).ready(function() { 

     var data = [ 
          { 
           "current_price": 1626.0, 
           "name": "HDFC Bank", 
           "industry": "Financials", 

          }, 
          { 
           "current_price": 7064.8, 
           "name": "Maruti Suzuki", 
           "industry": "Automobiles", 
          } 
         ]; 

     var test_data = ''; 
     $.each(data, function(key, val) { 
     test_data += '<tr>' ; 
     test_data += '<td>'+val.name+"</td>" ; 
     test_data += '<td>'+val.industry+"</td>" ; 
     test_data += '<td>'+val.current_price+"</td>" ; 
     test_data += '</tr>'; 
     }); 

     $('#test').append(test_data); 

}); 
+0

我的問題已經解決了!謝謝@Nawed汗 –

+0

我有一個查詢問! 可以說,我有很長的列表數組數據(10K記錄),我不能使用上述這種情況。 我該如何使用本地文件並將其轉換爲數組,然後做出相同的結果。 –

+0

很高興該解決方案爲您工作。從技術上講,你可以很好地使用上面的代碼來處理10K記錄,這將是非常長的文件。您可以將var data = [...]代碼放入另一個JS文件中,然後其他js文件將很長。通常10K記錄來自DataBase。最好的解決方案是使用ajax從數據庫加載數據。更好的是一次使用分頁/塊數據,因此您不會遇到AJAX數據限制。 –