def*_*t__ 5 html javascript button
我有三个 HTML 按钮,orders以及products和supplier。我希望当用户单击orders订单时显示,当用户单击时products显示产品,以及单击时显示供应商的名称。
function changedata(parameter){
if(parameter==0){
document.getElementById('myorders').style.fontSize="25px";
}
else if(parameter==1){
document.getElementById('myproducts').style.fontSize="25px";
}
else{
document.getElementById('mysupplier').style.fontSize="25px";
}
}Run Code Online (Sandbox Code Playgroud)
<button class="button" onclick="changedata(0)">ORDERS</button>
<button class="button" onclick="changedata(1)">PRODUCTS</button>
<button class="button" onclick="changedata(2)">SUPPLIER</button>
<div id="myorders">
<p>Laptop, Earphone</p>
</div>
<div id="myproducts">
<p>Earphone, smart watch</p>
</div>
<div id="mysupplier">
<p>Amazon, E-kart</p>
</div>Run Code Online (Sandbox Code Playgroud)
但它不会隐藏数据并满足我的需求,我是网络开发的初学者,正在寻找仅在按下相应按钮时才显示数据的帮助。
有一些稍微简单的方法可以将每个按钮连接div到其相应的按钮,其中之一是使用数据属性。我们可以向每个按钮添加一个数据属性,该属性的文本与其id相应的div.
(我假设当您单击一个按钮时,所有其他按钮divs都会隐藏,只有它的div显示。)
这个示例使用了更现代的 JS 技术,但我将指导您完成这些技术,对所有内容进行注释,并在最后提供文档。您不必了解这里的所有内容,但您最终可能会遇到这些内容,因此您不妨现在就看一下它们。
以下是这一切如何运作的概述:
addEventListener.display为block- 最初所有面板的显示设置为none)。然后,根据按钮数据属性中的 id,它与其形成一个选择器,我们使用它来定位其相应的目标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');
}
}Run Code Online (Sandbox Code Playgroud)
.panel { display: none; }
.show { display: block; }
.button { text-transform: uppercase; }
.button:hover { cursor: pointer; background-color: #fffff0; }Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)
附加文档