gpt4 book ai didi

javascript - 点击分页时添加事件类

转载 作者:行者123 更新时间:2023-11-28 04:55:16 24 4
gpt4 key购买 nike

在我的幻灯片中,我想在单击时向每个分页按钮添加和删除事件类。我怎样才能用原生JS做到这一点。到目前为止我的代码:

//Pagination
var p = document.getElementById('pagination');
var phtml = '';

for(var i = 0; i < slides.length; i++) {
phtml+='<button>' + (i+1) + '</button>';
}

p.innerHTML = phtml; // create the pagination buttons

var pbuttons = p.querySelectorAll('button'); // grab all the buttons

for(var i = 0; i < pbuttons.length; i++) {
pbuttons[i].onclick = (function(n) {
pbuttons[i].classList.toggle('active');

return function(){
pauseSlideshow();
goToSlide(n);
};

})(i);
}

最佳答案

试试这个:

//Pagination
var p = document.getElementById('pagination');
var phtml = '';

for(var i = 0; i < slides.length; i++) {
phtml+='<button>' + (i+1) + '</button>';
}

p.innerHTML = phtml; // create the pagination buttons

var pbuttons = p.querySelectorAll('button'); // grab all the buttons
var activeButton = null; // ref to active button

for(var i = 0; i < pbuttons.length; i++) {
pbuttons[i].onclick = (function(n) {

return function(){
if(activeButton)
// delete class from old active button
activeButton.classList.remove('active');

// change ref, this is current button
activeButton = this;
// add class for new
activeButton.classList.add('active');
pauseSlideshow();
goToSlide(n);
};
})(i);
}

说明:
我们创建了变量来存储对事件分页按钮的引用。单击时,我们从旧的事件按钮中删除了类 active 并将引用更改为触发单击事件的按钮,然后我们将类 active 添加到更新的事件按钮

关于javascript - 点击分页时添加事件类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42598022/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com