有一些更简单的方法将每个div
连接到其相应的按钮,其中之一是使用data attributes.我们可以 for each 按钮添加一个数据属性,该按钮的文本与其对应的div
中的id
相匹配.
(我假设当你点击一个按钮时,其他divs
个按钮都被隐藏,只有div
个按钮显示.)
本例使用了更现代的JS技术,但我将指导您完成这些技术,对所有内容进行注释,并在最后提供文档.你不必理解这里的一切,但最终你可能会遇到这些事情,所以你不妨现在就看看.
下面简要介绍了这一切的工作原理:
- 从按钮中删除内联侦听器.现代JS使用
addEventListener
.
- 把纽扣包在一个容器里.我们将使用一种叫做event delegation的技术.我们没有将侦听器连接到每个按钮,而是将one连接到容器,这样可以捕获从其子元素"冒泡"DOM的任何事件.然后,我们可以在单击子元素时调用函数.
- 这个函数做了一些事情.首先,它判断单击的元素是否实际上是一个按钮.然后,它通过删除名为"show"的类来隐藏所有"面板"("show"将元素的
display
设置为block
-最初所有面板的显示设置为none
).然后基于按钮数据属性的id,它与之形成一个 Select 器,我们使用它来定位其相应的div
并应用"show"类.
// Cache out buttons container, and all of the panels
const buttons = document.querySelector('.buttons');
const panels = document.querySelectorAll('.panel');
// Add an event listener to the buttons container
buttons.addEventListener('click', handleClick);
// When a child element of `buttons` is clicked
function handleClick(e) {
// Check to see if its a button
if (e.target.matches('button')) {
// For every element in the `panels` node list use `classList`
// to remove the show class
panels.forEach(panel => panel.classList.remove('show'));
// "Destructure" the `id` from the button's data set
const { id } = e.target.dataset;
// Create a selector that will match the corresponding
// panel with that id. We're using a template string to
// help form the selector. Basically it says find me an element
// with a "panel" class which also has an id that matches the id of
// the button's data attribute which we just retrieved.
const selector = `.panel[id="${id}"]`;
// Select the `div` and, using classList, again add the
// show class
document.querySelector(selector).classList.add('show');
}
}
.panel { display: none; }
.show { display: block; }
.button { text-transform: uppercase; }
.button:hover { cursor: pointer; background-color: #fffff0; }
<div class="buttons">
<button data-id="myorders" class="button">Orders</button>
<button data-id="myproducts" class="button">Products</button>
<button data-id="mysupplier" class="button">Supplier</button>
</div>
<div class="panel" id="myorders"><p>Laptop, Earphone</p></div>
<div class="panel" id="myproducts"><p>Earphone, smart watch</p></div>
<div class="panel" id="mysupplier"><p>Amazon, E-kart</p></div>
其他文件