[英]How can i store all these codes in a variable
How can i keep all these codes in a variable?我如何将所有这些代码保存在一个变量中? I want to call this codes in another place.
我想在另一个地方调用这个代码。 I want to add a click event on this slideShow menu.
我想在这个幻灯片菜单上添加一个点击事件。 It's easy if i write all those codes in another click event function.
如果我在另一个点击事件函数中编写所有这些代码,这很容易。 But i don't want to do that, i want to call all this codes in a click event by uscing a variable
但我不想这样做,我想通过使用变量在点击事件中调用所有这些代码
function change() {
if (document.getElementsByClassName("sliderItems")[0].classList.contains("active")) {
document.getElementsByClassName("sliderItems")[1].classList.add("active");
document.getElementsByClassName("sliderItems")[0].classList.remove("active");
} else if (document.getElementsByClassName("sliderItems")[1].classList.contains("active")) {
document.getElementsByClassName("sliderItems")[2].classList.add("active");
document.getElementsByClassName("sliderItems")[1].classList.remove("active");
} else if (document.getElementsByClassName("sliderItems")[2].classList.contains("active")) {
document.getElementsByClassName("sliderItems")[3].classList.add("active");
document.getElementsByClassName("sliderItems")[2].classList.remove("active");
} else if (document.getElementsByClassName("sliderItems")[3].classList.contains("active")) {
document.getElementsByClassName("sliderItems")[4].classList.add("active");
document.getElementsByClassName("sliderItems")[3].classList.remove("active");
} else if (document.getElementsByClassName("sliderItems")[4].classList.contains("active")) {
document.getElementsByClassName("sliderItems")[1].classList.add("active");
document.getElementsByClassName("sliderItems")[4].classList.remove("active");
}
}
setInterval(change, 2000);
I don't sure what you mean with codes, I think you mean the array of sliderItems, if this is what you mean is very easy.我不确定你对代码的意思,我想你的意思是滑块项的数组,如果这是你的意思很容易。
var sliderItems = document.getElementsByClassName('sliderItems');
sliderItems[0].classList.add('active');
The big advantage of using a variable to store a DOM element is better performance than searching the element every single time you want to use it.使用变量来存储 DOM 元素的最大优点是性能比每次要使用它时都搜索元素要好。
just assign setInterval(change, 2000)
to a variable and use it只需将
setInterval(change, 2000)
分配给一个变量并使用它
add to your script添加到您的脚本中
var listenChange = setInterval(change, 2000)
use it in your html在你的 html 中使用它
<button onclick="listenChange()">Button1</Button>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.