1 回答

TA貢獻1829條經驗 獲得超4個贊
您遇到的問題是由于您使用querySelectorAll
which 不僅選擇第一層子節點,而且會直接鉆入 DOM 并檢索所有匹配的節點。一個簡單的解決方案可能是通過添加屬性來區分子選項卡和父選項卡,并為子項使用單獨的處理程序。更全面的方法可能只涉及對頂級選項卡和選項卡內容進行操作。
(為了其他用戶的可讀性,我在代碼中添加了英文注釋并刪除了外國注釋)
'use strict';
document.addEventListener('DOMContentLoaded', function () {
var tabs = document.getElementsByClassName('tabs');
if (tabs) {
var _loop = function _loop() {
var tabListItems = tabs[i].querySelectorAll('li');
tabListItems.forEach(function (tabListItem) {
tabListItem.addEventListener('click', function (e) {
// Select any siblings of the current tab.
let siblings = Array.from(tabListItem.parentElement.children);
// Remove the is-active status from all siblings
siblings.forEach(function (element) {
element.classList.remove('is-active');
});
// Add the is-active status to the selected tab.
tabListItem.classList.add('is-active');
var tabName = tabListItem.dataset.tab;
// Same as above, rather than selecting all of the js-tab-content
// elements, we only select those which are at the same level as
// the selected tab.
let tabsContainer = tabListItem.closest('.js-tabs-container');
let tabsContainerChildren = Array.from(tabsContainer.children);
// Filter out other children that aren't js-tab-content elements.
let tabs = tabsContainerChildren.filter(function(el) {
return el.className.includes('js-tab-content')
});
tabs.forEach(function(tabContent) {
if (tabContent.id !== tabName) {
tabContent.classList.add('has-display-none');
} else {
tabContent.classList.remove('has-display-none');
}
})
}, false);
});
};
for (var i = 0; i < tabs.length; i++) {
_loop();
}
}
});
假設您的結構大體保持不變,這對于任何級別的嵌套選項卡都應該正確運行,因為選擇選項卡時唯一受影響的項目是它周圍的屏幕和鏈接。
重構
使用箭頭函數,并在不需要的地方分配較少的變量將使您能夠編寫更短更簡潔的代碼。這是一個示例,不一定是編寫它的最佳方式,但它可能會給您一些提取函數和鏈接數組迭代的想法。
document.addEventListener('DOMContentLoaded', () => {
Array.from(document.getElementsByClassName('tabs')).forEach(tab => {
tab.querySelectorAll('li').forEach(listItem => {
listItem.addEventListener('click', tabClickHandler(listItem), false);
});
});
});
function tabClickHandler (listItem) {
return () => {
let siblings = Array.from(listItem.parentElement.children);
siblings.forEach(el => el.classList.remove('is-active'));
listItem.classList.add('is-active');
let tabName = listItem.dataset.tab;
Array.from(listItem.closest('.js-tabs-container').children)
.filter(el => el.classList.contains('js-tab-content'))
.forEach(tab => {
if (tab.id !== tabName) {
tab.classList.add('has-display-none');
} else {
tab.classList.remove('has-display-none');
}
});
}
}
添加回答
舉報