javascript - 按钮不在选项卡之间共享操作
问题描述
我正在使用 Onsen UI 框架。我有一个包含 3 个选项卡(tab1、tab2 和 tab3)的 HTML 应用程序。所有代码都在同一个 HTML 文件下。在TAB1中,我有一个按钮,该按钮在检查时,H2会更改颜色。此更改仅在 tab1 上进行,但我希望更改所有三个选项卡。
基本上,这是一个想法:
HTML
<template id="tab1.html">
<ons-page id="tab1">
<!-- This is the button --> <ons-switch id="nightmode"></ons-switch>
</ons-page id="tab1">
<h2 class="title">Home</h2>
</template id="tab1.html">
<template id="tab2.html">
<ons-page id="tab2">
<h2 class="title">Home</h2><!-- It shall change colour, but it does not -->
</ons-page id="tab2">
</template id="tab2.html">
<template id="tab3.html">
<ons-page id="tab3">
<h2 class="title">Home</h2><!-- It shall change colour, but it does not -->
</ons-page id="tab3">
</template id="tab3.html">
JS
<script>
document.getElementById("nightmode").addEventListener("change", function() {
if (document.getElementById("nightmode").checked == true) {
document.getElementsByClassName("title")[0].setAttribute("style", "color: white;");
} else {
document.getElementsByClassName("title")[0].setAttribute("style", "color: black;");
}
});
</script>
解决方案
document.getElementsByClassName("title")[0].setAttribute("style", "color: black;");
此代码仅更改第一个元素,因为[0]
. 您可以使用此代码更改所有元素;
document.getElementById("nightmode").addEventListener("change", function() {
var elms = document.getElementsByClassName("title");
var textcolor = "white";
if(document.getElementById("nightmode").checked)
textcolor = "black";
for(var i in elms){
var elm = elms[i];
elm.style.color = textcolor;
}
});
另外,我建议使用 jQuery。使用jQuery,可以更简单;
$("#nightmode").change(function() {
if(this.checked)
$("h2.title").css("color", "white");
else
$("h2.title").css("color", "black");
}
推荐阅读
- javascript - 在插入之前检查 MongoDB 值是否存在
- c# - 选择项目后如何删除组合框
- c++ - 使用 CMake 查找本地目录库
- c++ - 我正在尝试以 1 + 2 的形式输入一个简单的数学表达式
- javascript - ES6,在访问“this”并在派生类中定义常量之前必须调用 super
- javascript - 通过反应在孩子中调用函数的孙子
- java - 在适用于 Linux 的 Windows 子系统 (WSL) 上安装 mitmproxy
- javascript - while 循环条件评估未按预期工作
- java - 扭曲排序
- python - 在python的while循环中更新“To:”电子邮件标题