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.

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

HTML:

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

4 个解决方案

#1


0

Create an outer div

创建一个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.

然后将查询选择器分配给div容器,并指定要跟踪的事件,如单击、更改等。

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

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

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.

您可以从事件的目标(如id、类、值等)访问任何内容。您可以评估发生的事件类型。你有更多的选择。

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.

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

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

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

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"

请注意代码的变化。为了解释“containerRouter”的目的,我将之前的代码移出该方法,并创建了一个名为“changeDisplay”的新方法

How it all works:

这一切是如何工作的:

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

    eventListner被添加到外部div“容器”中,因此当用户在容器内做任何事情时,就会触发一个事件。

  2. 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.

    eventListner发送所有您指定的事件的请求,如单击、更改、鼠标移动等到一个方法“containerRouter”。当它完成这个任务时,它的整洁部分会得到一个参数“e”。“e”事件。它附带了很多你可以使用的东西。

  3. 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”应该只包含将被触发事件引导到适当的方法/函数的代码。否则,你也可以像你在原来的文章中所说的那样,拥有一堆独立的事件监听器。

  4. 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.

    在“containerRouter”中,您可以评估“e”。什么样的事件。它是从哪里来的?是否存在与生成事件的对象相关的内容。这里有几个例子。当您离开文本字段时,您可以使用“更改”事件。您可以检查和验证内容。或者,如果有人在页面的某个区域上鼠标移动,你可以读取该对象的innerHTML,并显示它可以改变它。

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.

具体地说,我们在您的示例中所做的是在事件的目标id中查找子字符串“下拉”,目标是生成事件的对象,如按钮。你给每个按钮一个唯一的id,但也有一部分id是相同的,所以我们利用了这个。使用. indexof(“drop-button”)> -1的子字符串搜索方法,我们说如果这个条件为真,它必须是一个按钮。你可以谷歌indexOf。所以去做一些事情。在这种情况下,改变屏幕的显示。

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

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

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.

在changeDisplay方法中,我们要做的第一件事是使用方法。queryselecorall()。它提供了我们页面上所有与搜索条件匹配的所有对象的数组,其中

有一个名为“下拉”的类。这样我们就无需循环遍历页面上的对象来收集信息。现在我们快速地引用了所有这些对象。一个简单的循环通过并关闭它们,即使它们已经关闭。

更多相关文章

  1. jQuery Ajax未能调用MVC 4控制器方法。
  2. 在contenteditable中的占位符—焦点事件问题
  3. 当函数在单独的PHP文件中定义时,调用JavaScript函数onclick按钮事
  4. 如何在v模型更改时触发事件? (vue js)
  5. 使用python实现菱形的两种方法
  6. Win7 64为Sublime Text3 配置python3的开发环境的方法
  7. 更简单的方法来启用详细日志记录
  8. Python安装模块(numpy等)问题的两种解决办法——常规方法和Anacond
  9. python魔法方法、构造函数、序列与映射、迭代器、生成器

随机推荐

  1. Android 源码编译如何确定模块安装的位置
  2. Android Dimension
  3. EditText focus
  4. android添加广告之--admob
  5. android 文件存储注意点
  6. android第一天
  7. Android 常见广告库包名合集
  8. Android上积累代码
  9. Android设计登录界面、找回密码、注册功
  10. Android Lint