我正在使用Json數據來使用它填充Html表。當我排除
function getAllDepts()
{
,但我想插入一個按鈕,以便將填充新的JSON數據的HTML表格是availaible並刷新表的代碼工作正常。
但是,我什麼都沒有爲我工作。
任何建議??
我的HTML代碼
<!DOCTYPE html>
<html>
<head>
\t <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
\t <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
\t <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
\t
</head>
<body>
<div class="container">
\t
<div class="table-responsive">
\t <h1>Json</h1>
\t <br/>
\t <table class="table table-bordered table-striped" id="employee_table">
\t \t <tr>
\t \t \t <th>Class</th>
\t \t \t <th>Time</th>
\t \t \t
\t \t </tr>
\t </table>
</div>
</div>
<input id="getAllDepts" type="button" value="Create Table From JSON" />
</body>
</html>
<script>
$(document).ready(function(){
var employee_data= '';
if(localStorage.myJSON !== undefined){
var myJSON = JSON.parse(localStorage.myJSON);
employee_data += '<tbody>';
$.each(myJSON, function(key, value){
employee_data += '<tr>';
employee_data += '<td>'+value.class+'</td>';
employee_data += '<td>'+value.time+'</td>';
employee_data += '</tr>';
});
employee_data += '</tbody>';
$('#employee_table').append(employee_data);
}
employee_data= ''; // empty employee_data
$('#getAllDepts').click(function() {
$.getJSON("https://api.myjson.com/bins/8qktd", function(data){
$("#yourtableid tbody").remove(); // Empty table before filling it with new data
localStorage.setItem(myJSON, JSON.stringify(data)); // Save new data in localStorage
$.each(data, function(key, value){
employee_data += '<tr>';
employee_data += '<td>'+value.class+'</td>';
employee_data += '<td>'+value.time+'</td>';
employee_data += '</tr>';
});
$('#employee_table').append(employee_data);
});
})
</script>
和我面臨的另一個問題是當它處於脫機狀態,[從那裏(當然,當我刪除功能getAllDepts(){的),它運行良好],在那種情況下,它只會在聯機的時候使用json數據填充表格,脫機時它不再工作,只顯示列標題。
我的JSON數據是
[
{
"id":"1",
"time":"10-15",
"class":"John Smith"
},
{
"id":"2",
"time":"10-15",
"class":"John Smith"
},
{
"id":"3",
"time":"10-15",
"class":"John Smith"
},
{
"id":"4",
"time":"10-15",
"class":"John Smith"
},
{
"id":"5",
"time":"10-15",
"class":"John Smith"
},
{
"id":"6",
"time":"10-15",
"class":"John Smith"
},
{
"id":"7",
"time":"10-15",
"class":"John Smith"
},
{
"id":"8",
"time":"10-15",
"class":"John Smith"
},
{
"id":"9",
"time":"10-15",
"class":"John Smith"
},
{
"id":"10",
"time":"10-15",
"class":"John Smith"
},
{
"id":"11",
"time":"10-15",
"class":"John Smith"
},
{
"id":"12",
"time":"10-15",
"class":"John Smith"
}
]
您是否將該腳本標籤放入HTML頁面中?你的HTML例子沒有顯示。 –
getAllDepts()函數處於一個封閉的範圍內,並且在頁面級別不可見。您的瀏覽器的開發控制檯可能告訴你這一點。由於你使用jQuery,所以使用jQuery。而不是內聯的'onclick'屬性,用jQuery攻擊點擊處理程序。 – David
*「它不工作」*不是一個適當的技術問題陳述。花一些時間閱讀[ask] – charlietfl