具有相同名称的多个按钮显示不同的div [英] Mutiple buttons with the same name showing different divs

查看:198
本文介绍了具有相同名称的多个按钮显示不同的div的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有大量的按钮,所有用来显示一个div之前,我的问题是,而不是有20个不同的JavaScript函数,所有做同样的事情,是可能与一个吗?默认情况下,我在CSS中将显示设置为none。

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">&#x25BC</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">&#x25BC</button>
</div>

JavaScript:

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'> 
 your other divs
</div>

然后为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);
};

将事件发送到路由器,以检测div容器中触及的内容并执行您的特定代码

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;

您可以访问事件目标中的任何内容,如id,class,value等。的事件发生。

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.

您可以将查询选择器分配给整个文档,或将范围缩小到 < tbody> 节点,例如,如果您使用按钮或文本字段动态填充表格,则可以使用此一个事件侦听器进行检查。

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

传递事件....(e),您的函数/方法/子例程可以使用它来获取或放置有用的信息。

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">&#x25BC</button>
  </div>
</div>

javaScript

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";
};

请注意代码中的更改。为了解释containerRouter的目的,我把上面的代码移出了该方法,并创建了一个名为changeDisplay的新方法

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"

如何工作: / p>

How it all works:


  1. eventListner被添加到外部divContainer中,因此只要用户在容器中执行了某个事件,

  1. the eventListner is added to the outer div "Container", so anytime the user does something inside the container an event is fired.

eventListner将您指定的事件的所有请求(例如点击,更改,鼠标悬停等)发送到一个方法containerRouter。整洁的部分,当它做这个containerRouter接收一个参数e。
e是事件。

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.

containerRouter应该只包含将触发事件指向适当方法/函数的代码。

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.

在containerRouter中,您可以评估e。什么样的事件。具体来自哪里。是否有与生成事件的对象相关联的内容。这里有几个例子。您可以在离开文本字段时使用更改事件。您可以检查和验证内容。

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.



请注意,当我们调用方法/函数changeDisplay时,我们沿着e发送,因为它仍然有东西,我们可以使用。

Notice that when we called the method/function changeDisplay we sent along "e", because it still has stuff we can use.

在changeDisplay方法中,我们做的第一件事是使用方法.querySelecorAll()。它给我们一个数组的所有对象在我们的页面上匹配的搜索条件是< div> 有一个类叫下拉。这节省了我们在页面上循环访问对象以收集信息的需要。所以现在我们有一个快速引用所有这些对象。一个简单的循环遍历,并关闭它们,即使它们已经关闭。

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.

接下来我们要弄清楚你的按钮是按下了。这是e派上用场。我们只是提取e.target.id的id值,然后剖析它找到数字。我们将该号码附加到< div id =dropdown> 我们想弹出,并按照我上面的解释完成。

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆