删除按钮在javascript中不能从视图中立即删除?

问题描述 投票:0回答:1

我有一个日历,我也让用户删除事件。然而,当删除按钮被按下时,它提示用户删除事件 - 他们说是。但是事件留在日历上(没有删除),但是当我刷新页面时,事件就不见了。任何人都可以看到我的javascript,我做错了什么。 谢谢你的帮助。

这里是我的代码。

      var PUBLIC_KEY = "PUBLIC_KEY",
        CALENDAR_ID = "CALENDAR_ID";

    var events = []
    events = parselocalstorage('events')
    var renderPopup = function (jsEvent, start, end, calEvent) {
        var $popup = $('#calendar-popup');
        var $eventForm = $('#event-form');
        $event = $('#event');
        var $selectedElmt = $(jsEvent.target);
        var relativeStartDay = start.calendar(null, { lastDay: '[yesterday]', sameDay: '[today]' });
        var endNextDay = '';
        if (relativeStartDay === 'yesterday') {
            endNextDay = '[Today at] ';
        }
        else if (relativeStartDay === 'today') {
            endNextDay = '[Tomorrow at] ';
        }
        else {
            endNextDay = 'dddd ';
        }





        $('.start-time').html(

             '<time datetime="' + start.format() + '">'
            + start.calendar(null, {
                lastWeek: 'L LT',
                nextWeek: 'dddd LT',
                sameElse: 'L LT'
            })
            + '</time>'
        );




        if (calEvent) {
            $eventForm.hide();

            $event.children('header').html(`<i class="fa fa-calendar-o"></i>`);
            $event.find('.location').text(calEvent.location ? calEvent.location : '(No location information.)');
            $event.find('.details').text(calEvent.details ? calEvent.details : '');
            $event.show();
        }

        else {
            $event.hide();
            $('#event-start').val(start.format('YYYY-MM-DD[T]HH:mm'));
            $eventForm.show();
        }
        var leftPosition = 0;
        var $prong = $('.prong');
        var prongPos = 0;
        if ($selectedElmt.hasClass('fc-highlight')) {
            leftPosition = $selectedElmt.offset().left - $popup.width() + ($selectedElmt.width() / 2);
            if (leftPosition <= 0) {
                leftPosition = 5;
                prongPos = $popup.width() - $selectedElmt.offset().left - 30
            }
            else {
                prongPos = 15;
            }
            $popup.css('left', leftPosition);
            $prong.css({
                'left': '',
                'right': prongPos,
                'float': 'right'
            });
        }
        else {
            leftPosition = jsEvent.originalEvent.pageX - $popup.width() / 2;
            if (leftPosition <= 0) {
                leftPosition = 5;
            }
            prongPos = jsEvent.originalEvent.pageX - leftPosition - ($prong.width() * 1.7);
            $popup.css('left', leftPosition);
            $prong.css({
                'left': prongPos,
                'float': 'none',
                'right': ''
            });
        }
        var topPosition = (calEvent ? jsEvent.originalEvent.pageY : $selectedElmt.offset().top) - $popup.height() - 15;
        if ((topPosition <= window.pageYOffset)
            && !((topPosition + $popup.height()) > window.innerHeight)) {
            $popup.css('top', jsEvent.originalEvent.pageY + 15);
            $prong.css('top', -($popup.height() + 12))
                .children('div:first-child').removeClass('bottom-prong-dk').addClass('top-prong-dk')
                .next().removeClass('bottom-prong-lt').addClass('top-prong-lt');
        }
        else {
            $popup.css('top', topPosition);
            $prong.css({ 'top': 0, 'bottom': 0 })
                .children('div:first-child').removeClass('top-prong-dk').addClass('bottom-prong-dk')
                .next().removeClass('top-prong-lt').addClass('bottom-prong-lt');
        }
        $popup.show();
        $popup.find('input[type="text"]:first').focus();
    }
    $(document).ready(function () {
         $('#calendar').fullCalendar({
           header: {
                left: 'title',
                right: 'prev,next today'
            },
            timezone: 'local',
            defaultView: 'month',
            allDayDefault: false,
            allDaySlot: false,
            slotEventOverlap: true,
            slotDuration: "01:00:00",
           slotLabelInterval: "01:00:00",
            snapDuration: "00:15:00",
            contentHeight: 700,
            scrollTime: "8:00:00",
            axisFormat: 'h:mm a',
            timeFormat: 'h:mm A()',
            selectable: true,
            events: function (start, end, timezone, callback) {
                let arr = parselocalstorage('events')
                callback(arr);
            },
            eventColor: '#1a73e8',
            eventClick: function (calEvent, jsEvent) {
                renderPopup(jsEvent, calEvent.start, calEvent.end, calEvent);
             },
             eventRender: function (event, element) {
                 element.append(`<span class='I_delete'><i class="fa fa-remove fa-2x"></i></span>`);

                 element.find(".I_delete").click(function () {
                     $('#calendar-popup').hide();
                     if (confirm('are you sure want to delete event?')) {
                         $('#calendar').fullCalendar('removeEvents', event._id);
                         var index = events.map(function (x) { return x.id; }).indexOf(event.id);
                         events.splice(index, 1);
                         localStorage.setItem('events', JSON.stringify(events));

                         events = parselocalstorage('events')

                     }
                 });








              $('#close-btnid').click(function () {
                    $('#simplemodal').hide();
                })
                var modal = document.getElementById('simplemodal')
                window.addEventListener('click', clickOutside)
                function clickOutside(e) {
                    if (e.target == modal) {
                        modal.style.display = 'none';
                    }
                }
            },
            select: function (start, end, jsEvent) {
                $('.btn-primary').css('opacity', 1)
                $('.btn-primary').click(function () {
                    renderPopup(jsEvent, start.local(), end.local());
                })
                renderPopup(jsEvent, start.local(), end.local());
            },
            load: function (options) {
                var result = $.Deferred();
                $.ajax({
                    data: { showDeleted: true },
                    dataType: "json",
                    url: [
                        "https://www.googleapis.com/calendar/v3/calendars/",
                        CALENDAR_ID,
                        "/events?key=",
                        PUBLIC_KEY
                    ].join("")
                }).done(function (response) {
                    result.resolve(response.items);
                });
                return result.promise();
            },
        });
        //event-form
        $('#event-form').on('submit', function (e) {
            e.preventDefault();
            $form = $(e.currentTarget);
            $title = $form.find('input#event-title');
           // $location = $form.find('input#eventname');
            $details = $form.find('textarea#event-details');
            $ID = '_' + Math.random().toString(36).substr(2, 9)
            events.push({
                id: $ID,
                title: $title.val(),
                 start: $form.find('input#event-start').val(),
             //  location: $location.val(),
                details: $details.val()
            });
            $title.val('');


            $details.val('');
            $form.parent().blur().hide();
            localStorage.setItem('events', JSON.stringify(events));
            $('#calendar').fullCalendar('refetchEvents');
        });
        //Set hide action for ESC key event


       $('#calendar-popup').on('keydown', function (e) {
            $this = $(this);
            console.log($this);
            if ($this.is(':visible') && e.which === 27) {
                $this.blur();
            }
        })
            //Set hide action for lost focus event
            .on('focusout', function (e) {
                $this = $(this);
                if ($this.is(':visible') && !$(e.relatedTarget).is('#calendar-popup, #calendar-popup *')) {
                    $this.hide();
                }
            });
    });


    function clearDialog() {
        $('.dialog').empty();
    }

    $('body').click(function (e) {
        if (!$(e.target).is("input, .close")) {
            $('.dialog').removeClass('open');
        }
    });
    // initDialog();
    function parselocalstorage(name) {
        var str = localStorage.getItem(name);
        var obj = JSON.parse(str) || []
        let arr = Object.keys(obj).map((k) => obj[k]) || []
        return arr
    } 
javascript jquery fullcalendar
1个回答
1
投票

你可以把$('#calendar').fullCalendar('refetchEvents');放在函数的最后,像这样。

element.find(".I_delete").click(function () {
                     $('#calendar-popup').hide();
                     if (confirm('are you sure want to delete event?')) {
                         $('#calendar').fullCalendar('removeEvents', event._id);
                         var index = events.map(function (x) { return x.id; }).indexOf(event.id);
                         events.splice(index, 1);
                         localStorage.setItem('events', JSON.stringify(events));

                         events = parselocalstorage('events')
                         $('#calendar').fullCalendar('refetchEvents');


                     }
                 });

我希望这能解决你的问题:)。


1
投票

这是因为你只更新了状态而不是视图。你需要重新渲染视图。像angular和react这样的框架可以自动检测状态变化并重新渲染。由于你使用的是Jquery,我假设你没有使用过任何类似的框架。由于你只发布了部分代码,我只能给你我最好的猜测,一种方法是调用你实现的渲染函数,或者选择日历并使用innerHTML更新。

© www.soinside.com 2019 - 2024. All rights reserved.