Mutiple buttons with the same name showing different divs(具有相同名称的多个按钮显示不同的 div)
问题描述
我有大量的按钮都用来在它之前显示一个 div,我的问题是不是有 20 个不同的 javascript 函数都做同样的事情,有可能用一个吗?默认情况下,我在 CSS 中将显示设置为无.
HTML:
<div class="col-lg-6 event-title"><span>特奥会统一单板滑雪决赛</span><dd>SLOPESTYLE</dd><div id="#dropdown"><h6>2016 年结果</h6><p>金奖 - Chris Klug &亨利·米斯<br>银 - 丹尼戴维斯 &扎克·埃尔德<br>青铜 - Hannah teter &戴娜衬衫</p></div></div><div class="col-lg-1"><button type="button" id = "#drop-button" class="btn btn-default btn-lrg">▼</button></div><div class="col-lg-6 事件标题"><span>特奥会统一单板滑雪决赛</span><dd>SLOPESTYLE</dd><div id="#dropdown1"><h6>2016 年结果</h6><p>金奖 - Chris Klug &亨利·米斯<br>银 - 丹尼戴维斯 &扎克·埃尔德<br>青铜 - Hannah teter &戴娜衬衫</p></div></div><div class="col-lg-1"><button type="button" id = "#drop-button1" class="btn btn-default btn-lrg">▼</button></div>
JavaScript:
document.getElementById("#drop-button").addEventListener("click", function(){document.getElementById("#dropdown").style.display="block";});document.getElementById("#drop-button1").addEventListener("click", function(){document.getElementById("#dropdown1").style.display="block";});
创建外层div
<div id='container'>你的其他 div</div>
然后将查询选择器分配给 div 容器并指定要跟踪的事件,例如 click 、 change 等.
var g = {};g.formClass = 函数(){/*用<body onload = g.c.assignEventListeners();>调用这个方法*/this.assignEventListners = 函数(){/*容器div中所有链接的事件监听器*/容器 = document.querySelector("#container");container.addEventListener("点击", g.c.containerRouter, false);container.addEventListener("改变", g.c.containerRouter, false);};
将事件发送到路由器,以检测 div 容器中的内容并执行您的特定代码
以下是一些示例,说明如何监控事件并决定要做什么.
this.containerRouter = function (e){if (e.target !== e.currentTarget){/*引用事件的目标id*/if (e.target.id.indexOf('drop-button')>-1)g.c.changeDisplay(e);/*引用事件的目标类以及事件的类型*/if (e.target.classList[0]=='selMe' && e.type=='click')document.getElementById(e.target.id).select();if (e.target.classList[1]=='subMe' && e.type=='change')g.c.subTotHrs(e);}e.stopPropagation();};this.changeDisplay = 函数(e){/** 获取所有<div>的列表文档中带有 class="dropdown" 的元素* 将它们存储在数组变量 x 中*/var x = document.querySelectorAll("div.dropdown");/*遍历数组并关闭所有下拉菜单*/for (var i = 0; i
您可以访问事件目标中的任何内容,例如 id、类、值等.您可以评估发生的事件类型.您可以选择更多.
您可以将查询选择器分配给整个文档或将范围缩小到 <tbody>
节点,例如,如果您使用按钮或文本字段动态填充表格,它们可以都用这个事件监听器检查
传递事件 ....(e) 并且您的函数/方法/子例程可以使用它来获取或放置有用的信息.
在此示例中,我将所有代码包装在一个全局对象中.您可以选择是否执行相同的操作,只需更改对您希望执行的函数/方法的引用.我包括了比你需要的更多的东西,只是为了展示一些可能性.
这是您的特定问题所需的代码
HTML
javaScript
函数assignEventListners(){容器 = document.querySelector("#container");container.addEventListener("点击", containerRouter, false);}功能容器路由器(e){if (e.target !== e.currentTarget)if (e.target.id.indexOf('drop-button')>-1)更改显示(e);e.stopPropagation();}函数更改显示(e){var x = document.querySelectorAll("div.dropdown");for (var i = 0; i
请注意代码中的更改.为了解释containerRouter"的用途,我将之前的代码从该方法中移出并创建了一个名为changeDisplay"的新方法
这一切是如何运作的:
eventListner 被添加到外部 div容器"中,因此只要用户在容器内执行某项操作,就会触发事件.
eventListner 将针对您指定的事件(如单击、更改、鼠标悬停等)的所有请求发送到一个方法containerRouter".这个 containerRouter 的简洁部分接收一个参数e".e"是事件.它附带了很多你可以使用的东西.
containerRouter"应该只包含将触发事件定向到适当方法/函数的代码.否则,您可能会像您在原始帖子中所说的那样拥有一堆单独的事件侦听器.
在containerRouter"中你可以评估e".什么样的事件.具体是从哪里来的.是否存在与生成事件的对象相关联的内容.这里有几个例子.当您离开文本字段时,您可以使用更改"事件.您可以检查和验证内容.或者,如果有人将鼠标悬停在页面的某个区域上,您可以读取该对象的 innerHTML 并显示它,然后进行任何更改.
特别是我们对您的示例所做的操作,我们在事件的目标 ID 中查找了一个子字符串下拉列表".目标是像按钮一样生成事件的对象.你给每个按钮一个唯一的 id.但也有一部分 id 完全相同,所以我们利用了这一点.使用 .indexOf('drop-button') > -1 的子字符串搜索方法,我们说如果该条件为真,则它必须是一个按钮.你可以google indexOf.所以去做点什么吧.在这种情况下,请更改屏幕的显示.
请注意,当我们调用方法/函数 changeDisplay 时,我们会发送e",因为它仍然有我们可以使用的东西.
在 changeDisplay 方法中,我们做的第一件事是使用方法 .querySelecorAll().它为我们提供了页面上与搜索条件匹配的所有对象的数组,即 <div>
有一个名为dropdown"的类.这使我们无需遍历页面上的对象来收集信息.所以现在我们可以快速参考所有这些对象.即使它们已经关闭,一个简单的循环也会遍历并关闭它们.
接下来我们必须弄清楚你的哪个按钮被按下了.这就是e"派上用场的地方.我们只是提取 e.target.id 的 id 值,然后对其进行剖析以找到数字.我们将数字附加到我们想要弹出的 <div id="dropdown">
上,瞧,正如我上面解释的那样.
I have a large amount of buttons all used to display a div before it, my question is instead of having 20 different javascript functions which all do the same thing, is it possible to do with one? By default i have the display set to none in the CSS.
HTML:
<div class="col-lg-6 event-title">
<span>Special Olympics Unified Snowboarding Final</span>
<dd>SLOPESTYLE</dd>
<div id ="#dropdown">
<h6>2016 RESULTS</h6>
<p>
GOLD - Chris Klug & Henry Meece<br>
SILVER - Danny Davis & Zach Elder<br>
BRONZE - Hannah teter & Daina Shilts
</p>
</div>
</div>
<div class="col-lg-1">
<button type="button" id = "#drop-button" class="btn btn-default btn-lrg">▼</button>
</div>
<div class="col-lg-6 event-title">
<span>Special Olympics Unified Snowboarding Final</span>
<dd>SLOPESTYLE</dd>
<div id ="#dropdown1">
<h6>2016 RESULTS</h6>
<p>
GOLD - Chris Klug & Henry Meece<br>
SILVER - Danny Davis & Zach Elder<br>
BRONZE - Hannah teter & Daina Shilts
</p>
</div>
</div>
<div class="col-lg-1">
<button type="button" id = "#drop-button1" class="btn btn-default btn-lrg">▼</button>
</div>
JavaScript:
document.getElementById("#drop-button").addEventListener("click", function(){
document.getElementById("#dropdown").style.display="block";
});
document.getElementById("#drop-button1").addEventListener("click", function(){
document.getElementById("#dropdown1").style.display="block";
});
解决方案 Create an outer div
<div id='container'>
your other divs
</div>
then assign a query selector to the div container and specify what events you want to track like click , change etc.
var g = {};
g.formClass = function()
{
/*call this method with <body onload = g.c.assignEventListeners();>*/
this.assignEventListners = function()
{
/*event listener for all links in the container div*/
container = document.querySelector("#container");
container.addEventListener("click", g.c.containerRouter, false);
container.addEventListener("change", g.c.containerRouter, false);
};
send the events to a router, to detect what was touched in the div container and execute your specific code
Here are some examples of how you can monitor the events and make decision on what you want to do.
this.containerRouter = function (e)
{
if (e.target !== e.currentTarget)
{
/*Reference the event's target id*/
if (e.target.id.indexOf('drop-button')>-1)
g.c.changeDisplay(e);
/*Reference the event's target class along with the type of event*/
if (e.target.classList[0]=='selMe' && e.type=='click')
document.getElementById(e.target.id).select();
if (e.target.classList[1]=='subMe' && e.type=='change')
g.c.subTotHrs(e);
}
e.stopPropagation();
};
this.changeDisplay = function(e)
{
/*
* Get a list of all <div> elements in the document with class="dropdown"
* store them in a array variable x
*/
var x = document.querySelectorAll("div.dropdown");
/*loop through the array and close all drop downs*/
for (var i = 0; i < x.length; i++ )
x[i].style.display="none";
/*
* use the .split( ) method to extract the button #
* this puts the parts into an array you can reference
*/
var divNum = e.target.id.split('drop-button');
document.getElementById('#dropdown'+divNum[1]).style.display="block";
};
}
g.c = new g.formClass;
You can access anything from the event's target like id, class, value etc. You can evaluate what type of event occurred. There simply are a whole lot more options available to you.
You can assign the query selector to the whole document or narrow down the scope to a <tbody>
node so for example, if you are dynamically populating a table with buttons or text fields they can all be checked with this one event listener
pass along the event ....(e) and your functions/methods/sub-routines can use it to get or place useful information.
In this example I wrapped all the code in a global object. You can choose to do the same or not, just change the references to the functions/methods you wish to execute. I included more than you needed just to show some of the possibilities.
Here is the code needed for your specific question
HTML
<div id ='container'>
<div class="col-lg-6 event-title">
<span>Special Olympics Unified Snowboarding Final</span>
<dd>SLOPESTYLE</dd>
<div id ="#dropdown1">
<h6>2016 RESULTS</h6>
<p>
GOLD - Chris Klug & Henry Meece<br>
SILVER - Danny Davis & Zach Elder<br>
BRONZE - Hannah teter & Daina Shilts
</p>
</div>
</div>
<div class="col-lg-1">
<button type="button" id = "#drop-button1" class="btn btn-default btn-lrg">▼</button>
</div>
</div>
javaScript
function assignEventListners(){
container = document.querySelector("#container");
container.addEventListener("click", containerRouter, false);
}
function containerRouter(e) {
if (e.target !== e.currentTarget)
if (e.target.id.indexOf('drop-button')>-1)
changeDisplay(e);
e.stopPropagation();
}
function changeDisplay(e)
{
var x = document.querySelectorAll("div.dropdown");
for (var i = 0; i < x.length; i++ )
x[i].style.display="none";
var divNum = e.target.id.split('drop-button');
document.getElementById('#dropdown'+divNum[1]).style.display="block";
};
Please note the change in the code. To explain the purpose of the "containerRouter", I have moved the previous code out of that method and created a new method called "changeDisplay"
How it all works:
the eventListner is added to the outer div "Container", so anytime the user does something inside the container an event is fired.
The eventListner sends all request for events you have specified like click, change, mouseover etc. to one method "containerRouter". The neat part when it does this containerRouter receives one parameter "e".
"e" is the event. And it comes with a lot of stuff you can use.
The "containerRouter" should only contain code that directs the fired event to the appropriate method/function. Otherwise you may as well have a bunch of separate event listeners as you stated in your original post.
In the "containerRouter" you can evaluate "e". What kind of event. Where specifically did it come from. Was there content associated with the object that generated the event. Here's a couple of examples. You could use the "change" event when you leave a text field. You could examine and validate the content. Or if someone mouses over an area of the page you could read the innerHTML of the object and display it change it whatever.
Specifically what we did with your example we looked for a sub string "drop-down" in the event's target id. The target is the object that generated the event like your buttons. You gave each button a unique id. But also there was a part of the ids that were all the same, so we took advantage of that. Using the substring search method of .indexOf('drop-button') > -1, we said if that condition was true it must be a button. You can google indexOf. So go do something. In this case change the display of the screen.
Notice that when we called the method/function changeDisplay we sent along "e", because it still has stuff we can use.
In the changeDisplay method the first thing we do is use the method .querySelecorAll(). It gives us an array of all the objects on our page that match the search criteria which is <div>
that have a class called "dropdown". This saves us the need to loop through the objects on the page to gather up the information. So now we have a quick reference to all those objects. A simple loop goes through and closes them all even if they are already closed.
Next we have to figure out which of your buttons was pushed. This is where "e" comes in handy. We just extract the id value of e.target.id and then dissect it to find the number. We attach the number to the <div id="dropdown">
we want to popup and voila it's done as I have explained above.
这篇关于具有相同名称的多个按钮显示不同的 div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:具有相同名称的多个按钮显示不同的 div
基础教程推荐
- Chart.js 在线性图表上拖动点 2022-01-01
- 如何使用JIT在顺风css中使用布局变体? 2022-01-01
- html表格如何通过更改悬停边框来突出显示列? 2022-01-01
- 如何使用TypeScrip将固定承诺数组中的项设置为可选 2022-01-01
- Vue 3 – <过渡>渲染不能动画的非元素根节点 2022-01-01
- 直接将值设置为滑块 2022-01-01
- Electron 将 Node.js 和 Chromium 上下文结合起来意味着 2022-01-01
- 用于 Twitter 小部件宽度的 HTML/CSS 2022-01-01
- 我可以在浏览器中与Babel一起使用ES模块,而不捆绑我的代码吗? 2022-01-01
- 自定义 XMLHttpRequest.prototype.open 2022-01-01