我需要在两个 div 之间无限次更改显示样式。第一次改变是正常的,但向后改变就不起作用了。 此外,我无法使用指向确定 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>
最佳答案
在代码中,每次调用 func() 时,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>
关于JavaScript改变两侧的显示样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29486236/