【问题标题】:how to create checkbox events that call jQuery functions on other pages?如何创建在其他页面上调用 jQuery 函数的复选框事件?
【发布时间】:2020-10-26 03:17:13
【问题描述】:

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

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

【问题讨论】:

  • “在其他页面调用函数”。你不能。当您离开一个页面时,它的所有脚本都消失了,并且加载下一页中的任何脚本,根本不知道前一页中的内容。考虑使用 localStorage 来存储您的主题偏好,您将需要在需要主题切换的每个页面上使用代码
  • 您不能使用第一个 php 文件上的复选框事件来更改第二个 php 文件。您必须在第一页上放置一个按钮和 onclick 功能,或者在第一页上使用会话,并对第二页上收到的会话设置条件。您还可以使用 Ajax 动态更改特定页面。
  • 我可以用 php 代替吗?

标签: php jquery css


【解决方案1】:

$(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>

【讨论】:

  • 这可能会有所帮助
猜你喜欢
  • 1970-01-01
  • 2023-03-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-09
  • 2019-09-09
相关资源
最近更新 更多