通常,当我编写切换函数(例如在 2 种背景颜色之间切换)时,我会使用全局变量作为标志。例如像这样 -
var flag = true;
function change()
{
if(flag)
{
document.getElementById("box").style.backgroundColor = "blue";
flag = false;
}
else
{
document.getElementById("box").style.backgroundColor = "red";
flag = true;
}
}
#box
{
width:100px;
height:100px;
background-color:red;
}
<h3>Click the box to toggle</h1>
<div id="box" onclick="change()"></div>
但是当我编写多个函数来切换各种属性时,全局变量的数量会增加,正如这些文章所述-
Article #1
Article #2
Article #3
必须避免使用全局变量。
所以我的问题是,编写像切换这样的简单函数的另一种方法是什么?
最佳答案
您可以通过使用 addEventListener 结合自执行的匿名函数绑定(bind)到点击事件来完成此操作。
(function(){
var flag = true;
document.getElementById('box').addEventListener('click', function() {
this.style.backgroundColor = flag ? "blue" : "red";
flag = !flag;
});
})();
#box
{
width:100px;
height:100px;
background-color:red;
}
<h3>Click the box to toggle</h1>
<div id="box"></div>
关于javascript - 在不使用全局变量的情况下切换 Javascript/jQuery 的适当方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29636731/