通过复选框更改样式

change style through checkbox

我正在做一个全日历项目。

我有这 2 个 checkboxes (Ore Personali e Assenze),当检查它们时它们应该隐藏事件,但目前它们没有这样做。

这是我的输入复选框:

<input type="checkbox" id="OP" name="calendario" value="OP">

这是我目前构建的函数

$(document).ready(function() {
            $('input[type="checkbox"]').click(function() {
                var checkBox = document.getElementById("OP");
                var x = document.getElementsByClassName("fc-event-container");
                if (checkBox.checked === true){
                    x.style.visibility = "visible !important";
                }else{
                    x.style.visibility = "hidden !important";
                }
            })
        })

我通过在互联网上查看来构建它,因为我是 JS 的新手并且不太了解,只是基本的东西。 它在 x.style 部分给出错误(告诉我未定义)。 有人可以向我解释我应该怎么做吗,因为在互联网上我只找到了这种方式,而其他一些人只是给我错误。

提前感谢谁会帮助我(或至少尝试)


我按照@Cypherjac 的建议做了并且成功了。

但现在它只隐藏当月的事件,当我更改月份时,我必须选中和取消选中才能隐藏。即使我回到那个月我隐藏了他们可见的事件 有没有办法让他们即使我改变月份也能隐藏起来?


在我更新代码之前,我将指定这不是我的代码,我的完整日历来自我在互联网上找到的模板,我添加了我需要的功能,但大部分内容已经存在:

calendar.js代码:

key: 'handleFullcalendar',
    value: function handleFullcalendar() {
    
        var myOptions = {
            header: {
                left: 'today',
                center: 'prev,title,next',
                right: 'none',


            },
            
            buttonText:{
                today: 'Oggi',
                month: 'Mese',
                week: 'Settimana',
                day: 'Giorno'
            },
            
            locale:'it',        
            allDaySlot: false,  
            selectable: true,
            selectHelper: true,               
            timeFormat: 'H(:mm)',             
            editable: true,
            eventLimit: true,
            resourceAreaHeaderContent: 'Calendari',
            
            resources: [
                {
                    id: 'a',
                    title: 'Ore Personali'
                },
                {
                    id: 'b',
                    title: 'Assenze'
                }
            ],
            
            windowResize: function windowResize(view) {
                var width = $(window).outerWidth();
                var options = Object.assign({}, myOptions);

                options.events = view.calendar.clientEvents();
                options.aspectRatio = width < 667 ? 0.5 : 1.35;

                $('#calendar').fullCalendar('destroy');
                $('#calendar').fullCalendar(options);
            },
            
    //_______apre modal per aggiungere nuovo evento
        select: function select(event) {                
            $('#addNewEvent').modal('show');
            $('#calendar').fullCalendar('refetchEvents',event._id)
        },
            
    //_______________ELIMINARE EVENTO TRAMITE X
    
         eventRender: function(event, element, view) {
            if (view.name == 'listDay') {
                element.find(".fc-list-item-time").append("<span class='closeon'>X</span>");
            } else {
                element.find(".fc-content").prepend("<span class='closeon'>X</span>");
            }
            element.find(".closeon").on('click', function() {
                var deleteMsg = confirm("Vuoi davvero eliminare " + event.title + "?");
                if (deleteMsg == true) {                        
                    $.ajax({
                        url: 'eventi/deleteEvent.php',
                        type: 'POST',
                        data:  {_id: event.idAssenza, nomeUtente: event.nomeUtente},
                        success: function(html){
                            location.reload();
                        }
                    })
                    $('#calendar').fullCalendar('removeEvents',event._id);
                }else{
                    location.reload();
                }
            })
        }, 
                        
        //triggherà apertura modal di #editEvent
        eventClick: function eventClick(event) {
            var color = event.backgroundColor ? event.backgroundColor : (0, _Config.colors)('blue', 600);
            $('#editEname').val(event.title);
            $('event.id').val(event.idAssenza);
            $('nomeUtente').val(event.nomeUtente);
            $('#editStarts').val(event.start.toISOString());
            $('#editEnds').val(event.end.toISOString());
            $('#editNewEvent').modal('show').one('hidden.bs.modal', function (e) {
                event.title = $('#editEname').val();
                event.start = $('#editStarts').val();
                event.end = $('#editEnds').val();
                $.ajax({
                    url: 'eventi/updateEvent.php',
                    type: 'POST',
                    data:  {start: event.start, _id: event.idAssenza, end: event.end, title: event.title, },
                    success: function(html){
                        location.reload();
                    }
                });
                $('#calendar').fullCalendar('updateEvent', event._id);
            });
        }, 

            

            events: {                   
                url: 'eventi/load.php', 
                method:'POST'
                //color: <- fare in modo che prenda i colori scelti nel modal
                
            },
            droppable: false
        };
        
{       
    $(function() {
        $('#OP').change(function() {
            var x = $('.fc-event-container');
            // Access the element using jQuery
            if($(this).prop('checked')){
                x.css({
                    'visibility': 'visible'
                })
            }
            else {
                x.css({
                    'visibility': 'hidden'
                })
            }
        })
    });
},

        var _options = void 0;
        var myOptionsMobile = Object.assign({}, myOptions);

        myOptionsMobile.aspectRatio = 0.5;
        _options = $(window).outerWidth() < 667 ? myOptionsMobile : myOptions;

        $('#editNewEvent').modal();
        $('#calendar').fullCalendar(_options);
    }

Calendar.php:

    <?php 
  require_once "config.php";
  session_start(); 
   if(!ISSET($_SESSION['nomeUtente'])){
    header('location:login/login.php');
   }
?>

<!DOCTYPE html>
<html class="no-js css-menubar" locale="it">
  <head>

    <!-- Meta Tag -->
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimal-ui">
    <meta name="description" content="bootstrap material admin template">
    <meta name="author" content="">
    
    <title> Calendario | E.D. Elettronica Dedicata </title>
  </head>
  <body>

<div class="page">
      <div class="page-aside">
        <div class="page-aside-switch">
          <i class="icon md-chevron-left" aria-hidden="true"></i>
          <i class="icon md-chevron-right" aria-hidden="true"></i>
        </div>
        <div class="page-aside-inner page-aside-scroll">
          <div data-role="container">
            <div data-role="content">
<!--LISTA CALENDARI-->
              <section class="page-aside-section">
                <h5 class="page-aside-title">Lista calendari di <?php echo $_SESSION["nomeUtente"]; ?></h5>
                <div class="list-group has-actions">                  
                  <div class="list-group-item" data-plugin="editlist">
                    <div class="list-content">
                      <input type="checkbox" id="OP" name="calendario" value="OP" checked>
                      <span class="list-text"><a href="calendarOP.php">Ore Personali</a></span>
                    </div>                    
                  </div>
                  <div class="list-group-item" data-plugin="editlist">
                    <div class="list-content">
                      <input type="checkbox" id="assenze" name="calendario" value="assenze">
                      <span class="list-text"><a href="calendar.php">Assenze</a></span>                      
                    </div>
                    <div class="list-editable">
                    </div>
                  </div>
                </div>
              </section>

            </div>
          </div>
        </div>
      </div>
      <div class="page-main">
        <div class="calendar-container">
          <div id="calendar"></div>

<!--addEvent Dialog -->
          <div class="modal fade" id="addNewEvent" aria-hidden="true" aria-labelledby="addNewEvent"
            role="dialog" tabindex="-1">
            <div class="modal-dialog modal-simple">
              <form class="modal-content form-horizontal" action="eventi/addEvent.php" method="post" role="form">
                <div class="modal-header">
                  <button type="button" class="close" aria-hidden="true" data-dismiss="modal">×</button>
                  <h4 class="modal-title">Aggiungi Assenza (<?php echo $_SESSION["nomeUtente"]; ?>)</h4>
                </div>
                <div class="modal-body">
                  <div class="form-group row" id=editColor>
                    <label class="form-control-label col-md-2">Tipo:</label>
                    <input list="assenza" name="ename" id="ename" style="margin-left: 15px;" />
                    <datalist id="assenza">
                      <option value="Normali">
                        <option value="Straordinarie">
                      <option value="Ferie">
                      <option value="Malattia">
                      <option value="Permesso">
                        <option value="Smart Working">
                      <option value="Altro">
                    </datalist>
                    <input type="hidden" name="nomeUtente" id="nomeUtente" value="<?php echo $_SESSION["nomeUtente"]; ?>">                     
                  </div>
                  <div class="form-group row">
                    <label class="col-md-2 form-control-label" for="starts">Inizio:</label>
                    <div class="col-md-10">
                      <div class="input-group">
                        <input type="datetime-local" class="form-control" id="starts" name="starts" data-container="#addNewEvent">                 
                      </div>
                    </div>
                  </div>
                  <div class="form-group row">
                    <label class="col-md-2 form-control-label" for="ends">Fine:</label>
                    <div class="col-md-10">
                      <div class="input-group">
                        <input type="datetime-local" class="form-control" id="ends" name="ends" data-container="#addNewEvent">
                      </div>
                    </div>
                  </div>                  
                </div>
                <div class="modal-footer">
                  <div class="form-actions">
                    <input type="submit" class="btn btn-primary" value="Aggiungi Assenza">
                    <a class="btn btn-sm btn-white btn-pure" data-dismiss="modal" href="javascript:void(0)">Annulla</a>
                  </div>
                </div>
              </form>
            </div>
          </div>
          <!-- End AddEvent Dialog -->

<!-- editEvent Dialog -->
          <div class="modal fade" id="editNewEvent" aria-hidden="true" aria-labelledby="editNewEvent"
            role="dialog" tabindex="-1" data-show="false">
            <div class="modal-dialog modal-simple">
              <form class="modal-content form-horizontal" action="eventi/deleteEvent.php" method="POST" role="form">
                <div class="modal-header">
                  <button type="button" class="close" aria-hidden="true" data-dismiss="modal">×</button>
                  <h4 class="modal-title">Modifica Assenza (<?php echo $_SESSION["nomeUtente"]; ?>)</h4>
                </div>
                <div class="modal-body">
                  <div class="form-group row">
                    <label class="form-control-label col-md-2" for="editEname">Tipo:</label>
                    <input list="assenza" name="editEname" id="editEname" style="margin-left: 15px;" />
                    <datalist id="assenza">
                      <option value="Normali">
                        <option value="Straordinarie">
                      <option value="Ferie">
                      <option value="Malattia">
                      <option value="Permesso">
                        <option value="Smart Working">
                      <option value="Altro">
                    </datalist> 
                    <input type="hidden" name="nomeUtente" id="nomeUtente" value="<?php echo $_SESSION["nomeUtente"]; ?>">  
                  </div>                  
                  <div class="form-group row">
                    <label class="col-md-2 form-control-label" for="editStarts">Inizio:</label>
                    <div class="col-md-10">
                      <div class="input-group">
                        <input type="datetime-local" class="form-control" id="editStarts" name="editStarts" data-container="#editNewEvent">
                      </div>
                    </div>
                  </div>
                  <div class="form-group row">
                    <label class="col-md-2 form-control-label" for="editEnds">Fine:</label>
                    <div class="col-md-10">
                      <div class="input-group">
                        <input type="datetime-local" class="form-control" id="editEnds" name="editEnds"data-container="#editNewEvent">
                      </div>
                    </div>
                  </div>
                  
                </div>
                <div class="modal-footer">
                  <div class="form-actions">

                    <button class="btn btn-primary" data-dismiss="modal" type="button">Salva modifiche</button>
                    <a class="btn btn-sm btn-white btn-pure" data-dismiss="modal" href="javascript:void(0)">Annulla</a>
                  </div>                  
                </div>
              </form>
            </div>
          </div>
          <!-- End EditEvent Dialog -->

        </div>
      </div>
    </div>
      </body>
</html>

这是我正在使用的template,大部分代码都在那里,我只是更新了我正在使用和修改的部分

使用onchange事件

$(document).ready(function() {
    $('#OP').change(function() {
        var x = document.getElementsByClassName("fc-event-container");
        if (this.checked){
             x.style.visibility = "visible !important";
        }else{
             x.style.visibility = "hidden !important";
        }
    })
});

由于您已经在使用 jQuery,您可以使用它来访问元素而不是原生 js

这里$(this).prop('checked')是用来勾选checkboxchecked属性的

然后当它改变时,根据当前状态改变元素的可见性..

注意:最初选中该复选框是因为要切换的元素在文档加载时可见

$(function() {
    $('input[type="checkbox"]').on('change', function() {
        x = $('.fc-event-container')
        // Access the element using jQuery
        if($(this).prop('checked')){
            x.css({
                'visibility': 'visible'
            })
        }
        else {
            x.css({
                'visibility': 'hidden'
            })
        }
    })
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="fc-event-container">
    Toggle the checkbox to toggle me
</div>

<input type="checkbox" id="OP" name="calendario" value="OP" checked>


关于日历需要注意的一件事是,每次切换 , 事件再次渲染.. 因此,这意味着事件将具有默认状态,每次切换选项卡时都可以看到该状态

因此,如果您想确保元素保持隐藏状态,您必须仅在渲染后访问该元素,因为渲染是按顺序进行的,所以您不能在渲染开始后立即访问该元素,因为到那时您不知道什么时候渲染..

所以我介绍的概念只是使用 dayRender 日历的 属性 来检查内容渲染何时完成,并设置半个超时第二个 return 事件回到初始状态..

这就是概念,您可以通读文档找到一个事件,该事件将在所有日期渲染完成后触发,然后调用该函数将它们恢复为可见或隐藏状态

检查工作演示的codepen