简体   繁体   English

如何将各个按钮与各个div相关联?

[英]How do I associate individual buttons with individual divs?

I am trying to set up a web page where I have a list of buttons, and each button toggles the visibility of a div directly below it. 我试图建立一个网页,其中有一个按钮列表,每个按钮都在其下面切换div的可见性。

The problem I am having is that all of my buttons only toggle the visibility of the last div in my page. 我遇到的问题是我所有的按钮都只能切换页面中最后一个div的可见性。

Here is the following relevant code: 以下是相关代码:

HTML HTML

<div class="menuItem">
    <button>Food Item</button>
    <div class="info">
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
        <img src="../images/menu/spaghetti.jpg" alt="spaghetti">
    </div>
</div>
<div class="menuItem">
    <button>Food Item</button>
    <div class="info">
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
        <img src="../images/menu/spaghetti.jpg" alt="spaghetti">
    </div>
</div>
<div class="menuItem">
    <button>Food Item</button>
    <div class="info">
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
        <img src="../images/menu/spaghetti.jpg" alt="spaghetti">
    </div>
</div>

And here is my javascript: 这是我的JavaScript:

"use strict";

(function() {
    var menuItems = document.getElementsByClassName("menuItem");

    for(var ii = 0; ii < menuItems.length; ii++) {
        var button = menuItems[ii].getElementsByTagName("button")[0];
        var info = menuItems[ii].getElementsByClassName("info")[0];
        button.onclick = function() {
            if(info.style.display === "block") {
                info.style.display = "none";
            } else {
                info.style.display = "block";
            }
        };
    }
})();

I don't think I totally understand what the javascript is doing under the hood. 我不认为我完全理解javascript的功能。 I think I'm getting references to each individual button, but it seems like when I change the onclick method for one button, I am changing the onclick method for all of them. 我想我正在获取每个按钮的引用,但是当我为一个按钮更改onclick方法时,似乎为所有按钮都更改了onclick方法。 Why is this happening, and how do I prevent this? 为什么会发生这种情况,如何防止这种情况发生?

You can use jQuery to do so. 您可以使用jQuery来做到这一点。 You can define a function (let's call it toggleInfo and put it in onclick attribute like so: 您可以定义一个函数(让我们将其toggleInfo并将其放在onclick属性中,如下所示:

<button onclick="toggleInfo()">Food Item</button>

And then in your function you can use .toggle() on the nearest element with class info 然后在函数中,您可以在具有类info的最近元素上使用.toggle()

Try defining info within click handler using .nextElementSibling 尝试使用.nextElementSiblingclick处理程序中定义info

 (function() { "use strict"; var menuItems = document.getElementsByClassName("menuItem"); for (var ii = 0; ii < menuItems.length; ii++) { var button = menuItems[ii].getElementsByTagName("button")[0]; button.onclick = function() { var info = this.nextElementSibling; if (info.style.display === "block") { info.style.display = "none"; } else { info.style.display = "block"; } }; } })(); 
 .info { display: none; } 
 <div class="menuItem"> <button>Food Item</button> <div class="info"> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p> <img src="../images/menu/spaghetti.jpg" alt="spaghetti"> </div> </div> <div class="menuItem"> <button>Food Item</button> <div class="info"> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p> <img src="../images/menu/spaghetti.jpg" alt="spaghetti"> </div> </div> <div class="menuItem"> <button>Food Item</button> <div class="info"> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p> <img src="../images/menu/spaghetti.jpg" alt="spaghetti"> </div> </div> 

Event Delegation 活动委托

There is a much simpler way to do that. 有一种更简单的方法可以做到这一点。 Add a parent container 添加父容器

<div id="container">
<div class="menuItem">
.....

Create a custom Click handler for the parent container 为父容器创建自定义Click处理程序

function handler(e){
 console.dir(e.target);//maybe console.log(e.target);
 // or console.dir(e.target.parentNode);
}
document.getElementById('container').addEventListener('click',handler,false);

Check console while you click. 单击时检查控制台。 there are many useful informations about the clicked element's and it's parentNode 关于clicked元素及其parentNode有很多有用的信息


In your case: 在您的情况下:

function handler(e){
 if(e.target.nodeName=='BUTTON'){//if i click on the correct element
   e.target.parentNode.getElementsByClassName('info')[0].classList.toggle('view');
 }
}

classList nodeName parentNode target classList nodeName parentNode 目标

here is the custom hide class. 这是自定义的隐藏类。

.view{
 display:none;
}

I also would avoid display:none the browser needs to redraw the whole element everytime.think of top:-999999px; opacity:0; height:justthebuttonsize; transform:scale(0); 我也避免display:none浏览器每次都需要重top:-999999px; opacity:0; height:justthebuttonsize; transform:scale(0);整个元素。 top:-999999px; opacity:0; height:justthebuttonsize; transform:scale(0); top:-999999px; opacity:0; height:justthebuttonsize; transform:scale(0);

The cool part of this is that you have only one Event! 最酷的部分是您只有一个活动! No loops! 没有循环! And many more advantages. 还有更多优势。 You don't even need document.getElementsByClassName if you navigate trough the nodes (which is much faster).Ahh and this is everything pure native javascript. 如果您通过节点浏览(甚至更快),您甚至不需要document.getElementsByClassName嗯,这就是纯本机javascript。

http://jsfiddle.net/z6kk5rxc/2/ http://jsfiddle.net/z6kk5rxc/2/

if you don't understand something just ask 如果你不明白什么,那就问

Using jQuery, this is simple: 使用jQuery,这很简单:

$('.toggle').click(function() {
    $(this).next().toggle();
});

I added ' class="toggle" ' to each button. 我在每个按钮上添加了“ class =“ toggle”“。 Here's a fiddle: https://jsfiddle.net/mckinleymedia/tx4tsvfa/ 这是一个小提琴: https : //jsfiddle.net/mckinleymedia/tx4tsvfa/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM