【问题标题】:Show/hide div only one at a time一次只显示/隐藏一个 div
【发布时间】:2017-01-28 01:35:41
【问题描述】:

此代码是常见问题解答的原始版本,包含三个答案,单击它时可以显示或隐藏。我的任务是修改为一次只显示一个答案(其他两个必须关闭)。 我得到一个提示,使用 for 循环遍历数组中的 h2 元素,并删除所有不是被点击的 h2 元素的 class 属性。 谢谢,

"use strict";
var $ = function(id) { return document.getElementById(id); };

// the event handler for the click event of each h2 element

var toggle = function() {
    var h2 = this;                    // clicked h2 tag     
    var div = h2.nextElementSibling;  // h2 tag's sibling div tag




    // toggle plus and minus image in h2 elements by adding or removing a class
    if (h2.hasAttribute("class")) { 
        h2.removeAttribute("class");    
    } else { 
        h2.setAttribute("class", "minus"); 
    }

    // toggle div visibility by adding or removing a class
    if (div.hasAttribute("class")) { 
        div.removeAttribute("class");
    } else { 
        div.setAttribute("class", "open"); 
    } 
};

window.onload = function() {
    // get the h2 tags
    var faqs = $("faqs");
    var h2Elements = faqs.getElementsByTagName("h2");

    // attach event handler for each h2 tag     
    for (var i = 0; i < h2Elements.length; i++ ) {
        h2Elements[i].onclick = toggle;
    }


    // set focus on first h2 tag's <a> tag
    h2Elements[0].firstChild.focus();       
};

【问题讨论】:

  • 设计第一,代码第二!在设计中,您需要考虑诸如单击 h2 元素中的链接是否会导航到另一个页面、如果用户单击已打开的答案该怎么办、是否需要处理两个以上的 h2 元素以及是否那么,为什么onload 函数内的点击处理程序不能访问h2 元素的集合。祝你作业好运:)
  • 谢谢 :) 我会确保在编码之前写出伪代码))

标签: javascript arrays loops


【解决方案1】:

脚本的 HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>FAQs</title>
    <link rel="stylesheet" href="main.css">
    <script src="faqs.js"></script>     
</head>

<body>
    <main id="faqs">
        <h1>JavaScript FAQs</h1>
        <h2><a href="#" >What is JavaScript?</a></h2>
        <div>
            <p>JavaScript is a programming language that's built into the major web browsers.
                It makes web pages more responsive and saves round trips to the server.
            </p>
        </div>
        <h2><a href="#">What is jQuery?</a></h2>
        <div>
            <p>jQuery is a library of the JavaScript functions that you're most likely 
               to need as you develop web sites.
            </p>
        </div>
        <h2><a href="#">Why is jQuery becoming so popular?</a></h2>
        <div>
            <p>Three reasons:</p>
            <ul>
                <li>It's free.</li>
                <li>It lets you get more done in less time.</li>
                <li>All of its functions are cross-browser compatible.</li>
            </ul>
        </div>
    </main>
</body>
</html>

脚本的 CSS:

* {
    margin: 0;
    padding: 0;
}
body {
    font-family: Verdana, Arial, Helvetica, sans-serif;
    font-size: 87.5%;
    width: 650px;
    margin: 0 auto;
    border: 3px solid blue;
    padding: 15px 25px;
}
h1 { 
    font-size: 150%;
}
h2 {
    font-size: 120%;
    padding: .25em 0 .25em 25px;
    cursor: pointer;
    background: url(images/plus.png) no-repeat left center;
}
h2.minus {
    background: url(images/minus.png) no-repeat left center;
}
a {
    color: black;
    text-decoration: none; 
}
a:focus, a:hover { 
    color: blue; 
}
div {
    display: none;
}
div.open {
    display: block;
}
ul {
    padding-left: 45px;
}
li {
    padding-bottom: .25em;
}
p {
    padding-bottom: .25em;
    padding-left: 25px;
}

【讨论】:

    【解决方案2】:

    假设您现有的脚本/标记当前正在工作,类似以下的内容可能会起到作用。没有 HTML/CSS,我无法测试我的答案。

    本质上,它只是在单击时迭代常见问题项目,如果它们不是被单击的元素,则隐藏它们,或者如果它是被单击的元素则显示 - 如果单击相同的元素两次,它不会切换 - 一个将始终保持打开状态。

    "use strict";
        var $ = function(id) { return document.getElementById(id); };
    
        // the event handler for the click event of each h2 element
    
        window.onload = function() {
            // get the h2 tags
            var faqs = $("faqs");
            var h2Elements = faqs.getElementsByTagName("h2");
          
            function accordionClick(){
               var h2;
               for(var i=0; i < h2Elements.length; i++){
                 h2 = h2Elements[i]; 
                 if(h2 == this){ // The item we clicked
                   if(!h2.hasAttribute("class")){ // If it's open
                     closeItem(h2);
                   } else{ // If not 
                     openItem(h2); 
                   }
                 } else{ // Not the item we clicked so it should be closed
                   closeItem(h2);
                 }
               }
            }
          
            function openItem(h2){
                var div = h2.nextElementSibling;
                h2.removeAttribute("class")
                div.setAttribute("class", "open");
            }
          
            function closeItem(h2){
                var div = h2.nextElementSibling;
                h2.setAttribute("class", "minus")
                div.removeAttribute("class");
            }
          
            // attach event handler for each h2 tag and init classes     
            for (var i = 0; i < h2Elements.length; i++ ) {
                h2Elements[i].onclick = accordionClick;
                closeItem(h2Elements[i]);
            }
    
            // set focus on first h2 tag's <a> tag
            h2Elements[0].firstChild.focus();       
        };
    * {
        margin: 0;
        padding: 0;
    }
    body {
        font-family: Verdana, Arial, Helvetica, sans-serif;
        font-size: 87.5%;
        width: 650px;
        margin: 0 auto;
        border: 3px solid blue;
        padding: 15px 25px;
    }
    h1 { 
        font-size: 150%;
    }
    h2 {
        font-size: 120%;
        padding: .25em 0 .25em 25px;
        cursor: pointer;
        background: url(images/plus.png) no-repeat left center;
    }
    h2.minus {
        background: url(images/minus.png) no-repeat left center;
    }
    a {
        color: black;
        text-decoration: none; 
    }
    a:focus, a:hover { 
        color: blue; 
    }
    div {
        display: none;
    }
    div.open {
        display: block;
    }
    ul {
        padding-left: 45px;
    }
    li {
        padding-bottom: .25em;
    }
    p {
        padding-bottom: .25em;
        padding-left: 25px;
    }
    <main id="faqs">
            <h1>JavaScript FAQs</h1>
            <h2><a href="#" >What is JavaScript?</a></h2>
            <div>
                <p>JavaScript is a programming language that's built into the major web browsers.
                    It makes web pages more responsive and saves round trips to the server.
                </p>
            </div>
            <h2><a href="#">What is jQuery?</a></h2>
            <div>
                <p>jQuery is a library of the JavaScript functions that you're most likely 
                   to need as you develop web sites.
                </p>
            </div>
            <h2><a href="#">Why is jQuery becoming so popular?</a></h2>
            <div>
                <p>Three reasons:</p>
                <ul>
                    <li>It's free.</li>
                    <li>It lets you get more done in less time.</li>
                    <li>All of its functions are cross-browser compatible.</li>
                </ul>
            </div>
        </main>

    【讨论】:

    • 对不起,我不应该使用 live sn-p - 它会产生错误,因为不存在任何 DOM 元素,这意味着 h2Elementsfaqs 不会返回任何有用的东西和 @ 987654326@ 将失败。如果可以,请为您的脚本提供 HTML 和 CSS,我将更新答案以使其正常运行
    • 谢谢布赖恩!我现在将发布脚本的 HTML 和 CSS。抱歉回复晚了。
    • @Pappricot 不客气,我已经用你的 HTML 和 CSS 更新了我的示例,它似乎按我预期的方式运行 :)。如果还有其他问题,请告诉我,我会看看。
    • 感谢@Brian!:) 它运行完美!尽管我仍在尝试确定是否有一种方法可以组合切换功能并显示一个/隐藏所有功能。我将来会按照你的方式设计我的代码,我原来的代码设计甚至让我感到困惑:))
    • 不用担心,将打开/关闭函数分解成它们自己的函数可以让事情更整洁,然后给当前点击的项目添加一个条件来测试它是否打开,如果它已经打开,我们可以关闭它打开 :)。将你的代码组织成小的功能块是很好的——如果你看到我是如何从上一个版本重构到这个的——它几乎是一个复制+粘贴,将代码从if移动到function:)。
    猜你喜欢
    • 1970-01-01
    • 2016-10-13
    • 1970-01-01
    • 2015-07-21
    • 2012-04-30
    • 2012-02-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多