首页 > 解决方案 > 按钮不在选项卡之间共享操作

问题描述

我正在使用 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>

标签: javascripthtmlonsen-ui

解决方案


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");
}

推荐阅读