[英]I am trying to optimize the first chunk of code. Why doesn't my approach work? What's the best approach to shorten the code?
The code I try to optimize:我尝试优化的代码:
function classToggle1() {
document.getElementById("div1").classList.toggle('fa-folder');
document.getElementById("div1").classList.toggle('fa-folder-open');
}
function classToggle2() {
document.getElementById("div2").classList.toggle('fa-folder');
document.getElementById("div2").classList.toggle('fa-folder-open');
}
function classToggle3() {
document.getElementById("div3").classList.toggle('fa-folder');
document.getElementById("div3").classList.toggle('fa-folder-open');
}
document.querySelector('#x').addEventListener('click', classToggle1);
document.querySelector('#y').addEventListener('click', classToggle2);
document.querySelector('#z').addEventListener('click', classToggle3);
My approach that doesn't work in browsers:我的方法在浏览器中不起作用:
function classToggle(x) {
document.getElementById(x).classList.toggle('fa-folder');
document.getElementById(x).classList.toggle('fa-folder-open');
}
document.querySelector('#xx').addEventListener('click', classToggle("div1"));
document.querySelector('#yy').addEventListener('click', classToggle("div2"));
document.querySelector('#zz').addEventListener('click', classToggle("div3"));
Here I pass in "div1" "div2" and "div3" as arguments.在这里,我将“div1”“div2”和“div3”作为 arguments 传递。 My understanding is that those two code chunks should behave the same?
我的理解是这两个代码块的行为应该相同?
In the first example you're passing in the function ( classToggle1
), and in the second you're invoking the function (which happens to return undefined
).在第一个示例中,您传入 function (
classToggle1
),而在第二个示例中,您正在调用 function (恰好返回undefined
)。 You can update the second to enlambda the call.您可以更新第二个以 enlambda 调用。
document.querySelector('#xx').addEventListener('click', () => classToggle("div1"));
Or或者
document.querySelector('#xx').addEventListener('click', function () { classToggle("div1"); })
This should work.这应该有效。
document.querySelector('#xx').addEventListener('click', () => classToggle("div1"));
document.querySelector('#yy').addEventListener('click', () => classToggle("div2"));
document.querySelector('#zz').addEventListener('click', () => classToggle("div3"));
The point is that, you are passing the output of the classToggle(x) instead of passing the function itself.关键是,您传递的是 classToggle(x) 的 output 而不是传递 function 本身。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.