首页 > 解决方案 > 如何创建在其他页面上调用 jQuery 函数的复选框事件?

问题描述

我想要在 theme.php 中的一个复选框来触发 front.php 中的一个函数,该函数将一个 css 文件从默认的白色背景更改为蓝色背景的蓝色。取消选中该复选框会将其恢复为默认值。我尝试了各种不同的方法,从将脚本放入 theme.php 到使用所有不同的 jQuery 函数将其移动到 front.php,包括加载、更改、单击、发布、使用 if/else、附加到前面的标题标签。 php ...没有任何作用。
在主题.php

<div class="main-content">
    <input type="checkbox" id="front"/>
    <label for="front">FrontEnd</label>
</div> 

并在front.php

const frontEnd = document.querySelector("#front");
frontEnd.addEventListener('change', function(e) {
    if(frontEnd.checked){
        var link = document.createElement("link");
        link.rel = "stylesheet";
        link.type = "text/css";
        link.href = "css/blue.css";
        document.getElementsByTagName("head")[0].appendChild(link);
    }else{
        var link = document.createElement("link");
        link.rel = "stylesheet";
        link.type = "text/css";
        link.href = "css/default.css";
        document.getElementsByTagName("head")[0].appendChild(link);
    }
});

关于我可能遗漏的任何提示?干杯。

标签: phpjquerycss

解决方案


$(document).ready(function($){
  $('#test').click(function(){
    $("#main-div").toggleClass('class-yellow');
  });
  // $('#test').prop('checked', true);  //Checks it
 // $('#test').prop('checked', false);  //Unchecks it
});
.class-yellow {
  background:yellow;
  width:200px;
  padding:10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='main-div'>
  <label for="test">adding style when click</label>
  <input type="checkbox" id='test'>
</div>


推荐阅读