1 回答
TA贡献1828条经验 获得超13个赞
将功能放在外面更好。主要是为了可读性和测试,但如果您的函数被调用很多次(例如数百次),那么每次重新定义甚至可能会影响性能。
您可以向侦听器添加箭头函数,它将使用正确的参数调用 focusListener。你可以这样做:
export const setFocusListenersForKeyboardNavigation = (glide) => {
const slides = glide._c.Html.slides;
for (let i = 0; i < slides.length; i++) {
const currentSlide = slides[i];
const slideButton = currentSlide.querySelector(".js-slide-button");
const slideLink = currentSlide.querySelector(".js-slide-link");
slideButton && slideButton.addEventListener('focus', (event) => {focusListener(event, glide)});
slideLink && slideLink.addEventListener('focus', (event) => {focusListener(event, glide));
}
};
const focusListener = (event, glide) => {
const activeIndex = glide._i;
const buttonIndex = event.target.dataset.slideIndex;
if (activeIndex !== parseInt(buttonIndex)) {
glide.go(`=${buttonIndex}`);
}
};
添加回答
举报