代码之家  ›  专栏  ›  技术社区  ›  Shovers_

如何在没有回发的情况下运行Jscript

  •  0
  • Shovers_  · 技术社区  · 7 年前

    我正在尝试在我的网页中构建一个“手风琴”风格的可折叠div,如w3c学校所述。。。 accordion description

    ASP:

    <div class="col-md-4">
            <button class="accordion">Section 1</button>
            <div class="content">
                <asp:Table ID="Consumable_table" runat="server">
                    <asp:TableHeaderRow>
                        <asp:TableHeaderCell>
                        <h2>
                            <u>Consumable Stock</u>
                        </h2>
                        </asp:TableHeaderCell>
                    </asp:TableHeaderRow>
                </asp:Table>
            </div>
        </div>
    

    CSS:

    .accordion {
    background-color: #eee;
    color: #444;
    cursor: pointer;
    padding: 18px;
    width: 100%;
    border: none;
    text-align: left;
    outline: none;
    font-size: 15px;
    transition: 0.4s;}
    
    .active, .accordion:hover {
    background-color: #ccc;}
    
    .content {
    padding: 0 18px;
    background-color: white;
    max-height: 0;
    overflow: hidden;
    transition: max-height 0.2s ease-out;}
    

    我添加了以下Jscript:

    $(document).ready(function () {
            var acc = document.getElementsByClassName("accordion");
            var i;
    
            for (i = 0; i < acc.length; i++) {
                acc[i].addEventListener("click", function () {
                    this.classList.toggle("active");
                    var panel = this.nextElementSibling;
                    if (panel.style.maxHeight) {
                        panel.style.maxHeight = null;
                    } else {
                        panel.style.maxHeight = panel.scrollHeight + "px";
                    }
    
                    return false;
                });
            }
        });
    

    代码似乎工作得很好,当我单击Accordion元素时,它会展开,但它似乎会发回,Accordion会再次折叠,不会显示。

    这与div中的ASP表有关吗?

    2 回复  |  直到 7 年前
        1
  •  1
  •   Szab    7 年前

    button 是在单击时提交表单(其类型为 submit 默认情况下)。您只需添加 type="button"

    <button class="accordion" type="button">Section 1</button>
    

    这应该可以解决问题——它表明按钮只是一个简单的可点击按钮,没有任何特殊操作。

    <button> vs. <input type="button" />. Which to use?

        2
  •  1
  •   Community Mohan Dere    5 年前

    1. 默认情况下,按钮行为类似于submit按钮,因此将发生回发。如果你想阻止回发,你可以使用下面的代码。

      <button class="accordion" onclick="return false;">Section 1</button>

    2. <button type="button" class="accordion">Section 1</button>