Mutiple buttons with the same name showing different divs

后端 未结 4 1739
名媛妹妹
名媛妹妹 2021-01-28 07:42

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 possi

4条回答
  •  孤街浪徒
    2021-01-28 08:31

    Create an outer div

    your other divs

    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 */
     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 
    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 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

    Special Olympics Unified Snowboarding Final
    SLOPESTYLE
    2016 RESULTS

    GOLD - Chris Klug & Henry Meece
    SILVER - Danny Davis & Zach Elder
    BRONZE - Hannah teter & Daina Shilts

    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:

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

    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.

    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.

    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.

    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

    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

提交回复
热议问题