简体   繁体   English

JavaScript更改了两侧的显示样式

[英]JavaScript change display style in both sides

I need to change display style infinity times between two div. 我需要在两个div之间更改显示样式的无限时间。 The first change is normal, but backwards change isn't working. 第一次更改是正常的,但向后更改不起作用。 Additionally, I can't use link to definite div, because I have several identical divs. 另外,我不能使用链接到确定的div,因为我有几个相同的div。

<script type="text/javascript">
    function func(el){
      if (smth != true) {var smth = false;}
      if (smth == false) {
         el.firstElementChild.style.display = 'none';
      el.lastElementChild.style.display = 'block';
        smth = true;
      } else {
        el.firstElementChild.style.display = 'block';
      el.lastElementChild.style.display = 'none';
        smth = false;
      }
    }
</script>


<div onClick="func(this)">
  <div>1</div>
  <div style="display:none;">2</div>
</div>

In the code, smth will be undefined every time the func() is called because it is not a global variable. 在代码中,每次调用func()都不会定义smth,因为它不是全局变量。 To fix this just make the smth global. 要解决此问题,只需将smth设置为全局。

<script type="text/javascript">
var smth = false;

function func(el){
  if (smth == false) {
     el.firstElementChild.style.display = 'none';
  el.lastElementChild.style.display = 'block';
    smth = true;
  } else {
    el.firstElementChild.style.display = 'block';
  el.lastElementChild.style.display = 'none';
    smth = false;
  }
}
</script>


<div onClick="func(this)">
  <div>1</div>
  <div style="display:none;">2</div>
</div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM