完整日历.js不会显示数组中的 JSON 事件



我的 ASP.NET 应用程序生成事件,现在只是将它们存储在HTML列表中,如下所示:

<ul id="eventsList">
<li>
{editable:false,id:1,title:"Demo",start:"2018-03-14T00:00:00"}
</li>
</ul>

我使用 javascript 将此列表转换为数组,如下所示:

var events = [];
$("#eventsList").find('li').each(function () {
events.push(this.innerText);
});
$('#eventCalendar').fullCalendar({
height: "parent",
events: events
});

但是,FullCalendar 不显示任何事件 - 尽管事件位于数组中,如下所述:https://fullcalendar.io/docs/events-array

我在这里错过了什么?

首先,当你使用innerText推送事件数据时,如下所示:

$("#eventsList").find('li').each(function () {
events.push(this.innerText);
});

它实际上是在推动一个string,而不是Fullcalendar所期望的事件object

要解决此问题,您可以使用JSON.parse函数将 JSON 字符串解析为对象。但问题是,从你上面的解释来看,<li>标签中的事件数据没有正确引用。

{editable:false,id:1,title:"Demo",start:"2018-03-14T00:00:00"}

要成为有效的 JSON 字符串,属性名称(如editableidtitlestart)必须正确括起来。要解决此问题,您可以使用replace和一些正则表达式将引号放在属性名称周围:

var properJSONString = eventString.replace(/([a-z]+):/g, '"$1":')

因此,为了总结这一点,您可以从<li>标签推送事件,如下所示:

$(document).ready(function () {
var events = [];
// Loop through each list.
$("#eventsList li").each(function () {
// Get the event data, which is a string.
var eventString = $(this).text().trim();
// Properly quote the key (property name), so it's a valid JSON string.
var jsonString = eventString.replace(/([a-z]+):/g, '"$1":');
// Parse it to object with JSON.parse() and push it to events variable.
events.push(JSON.parse(jsonString));
});
$('#calendar').fullCalendar({
height: "parent",
events: events
});
});

您可以在此处查看演示:hopeful-franklin-085848.bitballoon.com

但是,这不是一个干净的解决方案。FullCalendar已经提供了直接从服务器加载事件的功能。在此处阅读有关它的更多信息:事件(作为 JSON 源)。

希望这能给你一些想法。

最新更新