我試圖做到這一點,當我的程式從假期 API 接收新的 JSON 資料時,它可以用新資料替換來自 API 的舊資料。
我試圖在開始時將陣列宣告為空,但這不起作用。如果陣列 > 1,我也嘗試清空陣列,但這也不起作用。
我的代碼:
// Declares an empty array
var eventsArr = [];
console.log(eventsArr);
// Pushes the API data to an object
for(i = 0; i < result['data']['holidays'].length; i ){
let date = result['data']['holidays'][i]['date']['iso'];
eventsArr.push({
"startDate": new Date(date),
"endDate" : new Date(date),
"summary" : result['data']['holidays'][i]['description']
});
}
// Uses the pushed data to add the dates to the calendar
$("#calendar").simpleCalendar({
// Events displayed
displayEvent:true,
// Dates of the events
events: eventsArr
});
uj5u.com熱心網友回復:
我寫了一個你可以嘗試的片段:它在隨機事件時初始化日歷,每次點擊“重新加載”時都會重繪 3 個隨機元素。您可以跳過“模擬您的 API”部分,因為這只是為了讓我的代碼段每次都能處理新資料。
基本上,您需要做的是有一個函式來獲取事件并將它們包含在日歷中。然后可以在每次需要時呼叫此函式,而不是在打開頁面時僅獲取一次事件。
獲取事件后,此函式清空日歷并將新資料放入日歷中。
最后,很久以前來自 jQuery 世界,我強烈建議遷移到 VueJS,因為您將更輕松地構建更復雜的應用程式。
/*
Mocking of your API
*/
// to wait a bit
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
// to create random dates
function randomDate(start, end) {
return new Date(start.getTime() Math.random() * (end.getTime() - start.getTime()));
}
// to build an event
function mockEvent() {
const date = randomDate(new Date(2021, 9, 1), new Date(2021, 9, 31));
return {
startDate: date,
endDate: date,
summary: `EVENT ${Math.floor(100*Math.random())}`,
}
}
// to call the API
async function mockAPI() {
console.log('API call');
await sleep(3000);
return Array.from({length: 3}, (x) => mockEvent());
}
/*
Function to execute when you want to
initialize your calendar
*/
const initializeCalendar = async () => {
console.log('Calendar initialization');
/*
Here you call your API
*/
const events = await mockAPI();
console.log('Calendar filling');
let container = $("#calendar");
container.empty().data('plugin_simpleCalendar', null).simpleCalendar({
displayEvent: true,
events: events
});
}
// when you want to fetch elements
async function reload() {
console.log('Reloading');
await initializeCalendar();
}
/*
to properly initialize the calendar
*/
$(document).ready(function() {
console.log('FIRST INIT');
initializeCalendar();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://www.jqueryscript.net/demo/animated-event-calendar/dist/simple-calendar.css" rel="stylesheet"/>
<script src="https://www.jqueryscript.net/demo/animated-event-calendar/dist/jquery.simple-calendar.js"></script>
<button onclick="reload()">
Reload
</button>
<div id="calendar"></div>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/340044.html
標籤:javascript 查询 数组 目的 日历
