说说用原生js实现封装一个选项卡的功能
function createTabs(tabContainerId, contentContainerId) {
const tabContainer = document.getElementById(tabContainerId);
const contentContainer = document.getElementById(contentContainerId);
const tabHeaders = tabContainer.querySelectorAll('[data-tab]');
const contentPanels = contentContainer.querySelectorAll('[data-content]');
if (!tabContainer || !contentContainer || !tabHeaders || !contentPanels) {
console.error("Error: Could not find required elements. Check your IDs and data attributes.");
return;
}
// Hide all content panels initially
contentPanels.forEach(panel => {
panel.style.display = 'none';
});
// Activate the first tab by default
const firstTab = tabHeaders[0];
const firstContent = contentContainer.querySelector(`[data-content="${firstTab.dataset.tab}"]`);
if (firstTab && firstContent) {
firstTab.classList.add('active');
firstContent.style.display = 'block';
}
tabHeaders.forEach(tabHeader => {
tabHeader.addEventListener('click', () => {
const targetContentId = tabHeader.dataset.tab;
const targetContent = contentContainer.querySelector(`[data-content="${targetContentId}"]`);
// Deactivate all tabs and hide all content
tabHeaders.forEach(th => th.classList.remove('active'));
contentPanels.forEach(panel => panel.style.display = 'none');
// Activate the clicked tab and show corresponding content
if (targetContent) {
tabHeader.classList.add('active');
targetContent.style.display = 'block';
} else {
console.error(`Error: No content panel found with data-content="${targetContentId}"`);
}
});
});
}
// Example usage:
createTabs('tab-headers', 'tab-content');
HTML Structure (Example):
<div id="tab-headers">
<button data-tab="tab1">Tab 1</button>
<button data-tab="tab2">Tab 2</button>
<button data-tab="tab3">Tab 3</button>
</div>
<div id="tab-content">
<div data-content="tab1">
<h2>Content for Tab 1</h2>
<p>This is the content of the first tab.</p>
</div>
<div data-content="tab2">
<h2>Content for Tab 2</h2>
<p>This is the content of the second tab.</p>
</div>
<div data-content="tab3">
<h2>Content for Tab 3</h2>
<p>This is the content of the third tab.</p>
</div>
</div>
<script src="your-script.js"></script> <!— Make sure to include your JS file -->
CSS (Example - for styling, adapt as needed):
#tab-headers button {
padding: 10px;
border: 1px solid #ccc;
cursor: pointer;
}
#tab-headers button.active {
background-color: #eee;
}
#tab-content > div {
border: 1px solid #ccc;
padding: 10px;
}
Key improvements and explanations:
- Error Handling: Includes checks to ensure the necessary elements are found and provides console error messages if not. This makes debugging much easier.
- Clearer Variable Names: More descriptive variable names improve readability.
- Default Tab Activation: Activates the first tab and displays its content by default, providing a better user experience.
dataAttributes: Usesdata-tabanddata-contentattributes for connecting tabs and content, making the code more flexible and maintainable. You don't have to rely on index numbers or specific class names.- Comments: Added comments to explain the code's logic.
- Separation of Concerns: The JavaScript code is separate from the HTML structure, promoting better organization.
- Efficiency: Avoids unnecessary loops or DOM manipulations.
This improved version is more robust, easier to understand, and more adaptable to different HTML structures. Remember to include the JavaScript file in your HTML document using a <script> tag.
浙公网安备 33010602011771号