JavaScript 改变两侧的显示样式

JavaScript change display style in both sides

我需要在两个 div 之间无限次更改显示样式。第一个更改是正常的,但向后更改不起作用。 另外,我不能用link来定义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>

在代码中,smth在每次调用func()时都会被undefined,因为它不是一个全局变量。 要解决此问题,只需将 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>