按钮不共享选项卡之间的操作

问题描述 投票:1回答:1

我正在使用Onsen UI框架。我有一个HTML应用程序,其中包含3个选项卡(tab1,tab2和tab3)。所有代码都在同一个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>
javascript html onsen-ui
1个回答
1
投票
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");
}
© www.soinside.com 2019 - 2024. All rights reserved.