【问题标题】:JS/JQuery - Problem getting Expand/Collapse to workJS/JQuery - 让展开/折叠工作出现问题
【发布时间】:2021-06-19 08:26:07
【问题描述】:

我的 HTML 页面的手风琴部分无法正常工作。

问题

  1. 单击“全部展开”(变为“全部折叠”)不起作用。
  2. 当我单击“+”(标题旁边)时,它会展开标题,但单击另一个标题上的 +(当一个标题已经展开时)会导致前一个(或全部)关闭,并且只打开刚刚选中的那个。我需要标签保持打开状态,或者仅在用户单击“-”或单击“全部展开/全部折叠”按钮时关闭。

注意:我已经包含了完整的JS,包括我认为可能存在冲突的其他功能?

这里是JSFiddle

请帮忙,谢谢!

JS

var testing = {
  
    BContactUs: function() {
      var businessForm = document.getElementById('businesscontactus_form');
      const companyName = document.getElementById('companyName');
      const bRName = document.getElementById('bRName');
      const cPosition = document.getElementById('cPosition');
      const bEmail = document.getElementById('bEmail');
      const bMessage = document.getElementById('bMessage');
  
      businessForm.addEventListener('submit', e => {
        e.preventDefault();
  
        checkInputs();
      });
  
      function checkInputs() {
        // trim to remove the whitespaces
        const companyNameValue = companyName.value.trim();
        const bRNameValue = bRName.value.trim();
        const cPositionValue = cPosition.value.trim();
        const bEmailValue = bEmail.value.trim();
        const bMessageValue = bMessage.value.trim();
  
        if (companyNameValue === '') {
          setErrorFor(companyName, 'Company Name must be entered');
        } else {
          setSuccessFor(companyName);
        };
  
        if (bRNameValue === '') {
          setErrorFor(bRName, 'Name cannot be blank');
        } else {
          setSuccessFor(bRName);
        };
  
        if (bEmailValue === '') {
          setErrorFor(bEmail, 'Email cannot be blank');
        } else if (!isEmail(bEmailValue)) {
          setErrorFor(bEmail, 'Not a valid email');
        } else {
          setSuccessFor(bEmail);
        };
  
        if (cPositionValue === '') {
          setErrorFor(cPosition, 'C position cannot be blank');
        } else {
          setSuccessFor(cPosition);
        };
  
        if (bMessageValue === '') {
          setErrorFor(bMessage, 'Message cannot be blank');
        } else {
          setSuccessFor(bMessage);
        };
      };
  
      function setErrorFor(input, message) {
        const formControl = input.parentElement;
        const small = formControl.querySelector('small');
        formControl.className = 'bus-form-control error';
        small.innerText = message;
      };
  
      function setSuccessFor(input) {
        const formControl = input.parentElement;
        formControl.className = 'bus-form-control success';
      };
  
      function isEmail(bEmail) {
        return /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(bEmail);
      };
    },
    CustomerContactUs: function() { 
      const customer_contactus_form = document.getElementById('customercontactus_form');
      const cCUName = document.getElementById('cCUName');
      const cCUSubject = document.getElementById('cCUSubject');
      const cCUEmail = document.getElementById('cCUEmail');
      const cCUMessage = document.getElementById("cCUMessage");
      const cCUDisclaimerBox = document.getElementById('cCUDisclaimerBox');
  
      customer_contactus_form.addEventListener('submit', e => {
        e.preventDefault();
  
        checkcustomerCU_Inputs();
      });
  
      function checkcustomerCU_Inputs() {
        //trim to remove the whitespaces
        const cCUNameValue = cCUName.value.trim();
        const cCUSubjectValue = cCUSubject.value.trim();
        const cCUEmailValue = cCUEmail.value.trim();
        const cCUMessageValue = cCUMessage.value.trim();
  
        if (cCUNameValue === '') {
          setErrorForCU(cCUName, 'Please enter your name');
        } else {
          setSuccessForCU(cCUName);
        };
  
        if (cCUSubjectValue === '') {
          setErrorForCU(cCUSubject, 'Please enter a subject in order for us to help you better.');
        } else {
          setSuccessForCU(cCUSubject);
        };
  
        if (cCUEmailValue === '') {
          setErrorForCU(cCUEmail, 'Email cannot be blank');
        } else if (!isEmail(cCUEmailValue)) {
          setErrorForCU(cCUEmail, 'Not a valid email');
        } else {
          setSuccessForCU(cCUEmail);
        };
  
        if (cCUMessageValue === '') {
          setErrorForCU(cCUMessage, 'Please enter a message.');
        } else {
          setSuccessForCU(cCUMessage);
        };
  
        if (!cCUDisclaimerBox.checked) {
          setErrorForCU(cCUDisclaimerBox, 'Please check box and accept terms and conditions.');
        } else {
          setSuccessForCU(cCUDisclaimerBox);
        };
      };
  
      function setErrorForCU(input, message) {
        const formControlCU = input.parentElement;
        const small = formControlCU.querySelector('small');
        formControlCU.className = 'cus-form-control error';
        small.innerText = message;
      };
  
      function setSuccessForCU(input) {
        const formControl = input.parentElement;
        formControl.className = 'cus-form-control success';
      };
  
      function isEmailCU(cCUEmail) {
        return /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(cCUEmail);
      };
    }
  };
  
  
  $(document).ready(function() {
  
    $(".cp_exin_expandAll").on("click", function() {
      var accordionId = $(this).attr("accordion-id"),
        numPanelOpen = $(accordionId + ' .collapse.in').length;
  
      $(this).toggleClass("active");
  
      if (numPanelOpen == 0) {
        openAllPanels(accordionId);
      } else {
        closeAllPanels(accordionId);
      }
    })
  
    openAllPanels = function(aId) {
      console.log("setAllPanelOpen");
      $(aId + ' .panel-collapse:not(".in")').collapse('show');
    }
    closeAllPanels = function(aId) {
      console.log("setAllPanelclose");
      $(aId + ' .panel-collapse.in').collapse('hide');
    }
  
  });

HTML

<!doctype html>
<html lang="en">

  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- Bootstrap CSS -->
    <link rel="preconnect" href="https://fonts.gstatic.com">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <link rel="stylesheet" href="style.css">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
    <!-- Latest compiled and minified CSS -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/js/bootstrap.bundle.min.js " integrity="sha384-ygbV9kiqUc6oa4msXn9868pTtWMgiQaeYH7/t7LECLbyPA2x65Kgf80OJFdroafW " crossorigin="anonymous "></script>
    <script type="text/javascript" src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
    <script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
    <title>Extra Info</title>
  </head>

  <body>
    <header></header>

    <div class="extrainfo_outerbackground">
      <div class="extrainfo_banner">
        <h3 class="form-heading">Lorem Ipsum</h3>
        <a href="javascript:void(0)" class="cp_exin_expandAll active" accordion-id="#accordion"></a>
      </div>
      <div class="clearfix"></div>
      <div class="panel-group" id="accordion" role="tablist" aria-multiselectable="true">
        <div class="panel panel-default">
          <div class="panel-heading" role="tab" id="headingOne">
            <h4 class="panel-title">
              <a class="collapsed" role="button" data-toggle="collapse" data-parent="#accordion" href="#collapseOne" aria-expanded="true" aria-controls="collapseOne">
                Collapsible Group Item #1
              </a>
            </h4>
          </div>
          <div id="collapseOne" class="panel-collapse collapse in" role="tabpanel" aria-labelledby="headingOne">
            <div class="panel-body">
              <br>
              <p>
                Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird
                on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table,
                raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
              </p>
            </div>
          </div>
        </div>
        <div class="panel panel-default">
          <div class="panel-heading" role="tab" id="headingTwo">
            <h4 class="panel-title">
              <a class="collapsed" role="button" data-toggle="collapse" data-parent="#accordion" href="#collapseTwo" aria-expanded="true" aria-controls="collapseTwo">
                Collapsible Group Item #2
              </a>
            </h4>
          </div>
          <div id="collapseTwo" class="panel-collapse collapse in" role="tabpanel" aria-labelledby="headingTwo">
            <div class="panel-body">
              Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird
              on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table,
              raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
            </div>
          </div>
        </div>
        <div class="panel panel-default">
          <div class="panel-heading" role="tab" id="headingThree">
            <h4 class="panel-title">
              <a class="collapsed" role="button" data-toggle="collapse" data-parent="#accordion" href="#collapseThree" aria-expanded="true" aria-controls="collapseThree">
                Collapsible Group Item #3
              </a>
            </h4>
          </div>
          <div id="collapseThree" class="panel-collapse collapse in" role="tabpanel" aria-labelledby="headingThree">
            <div class="panel-body">
              Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird
              on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table,
              raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
            </div>
          </div>
        </div>
        <div class="panel panel-default">
          <div class="panel-heading" role="tab" id="headingFour">
            <h4 class="panel-title">
              <a role="button" data-toggle="collapse" data-parent="#accordion" href="#collapseFour" aria-expanded="true" aria-controls="collapseFour">
                Collapsible Group Item #4
              </a>
            </h4>
          </div>
          <div id="collapseFour" class="panel-collapse collapse in" role="tabpanel" aria-labelledby="headingFour">
            <div class="panel-body">
              Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird
              on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table,
              raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
            </div>
          </div>
        </div>
        <div class="panel panel-default">
          <div class="panel-heading" role="tab" id="headingFive">
            <h4 class="panel-title">
              <a class="collapsed" role="button" data-toggle="collapse" data-parent="#accordion" href="#collapseFive" aria-expanded="true" aria-controls="collapseFive">
                Collapsible Group Item #5
              </a>
            </h4>
          </div>
          <div id="collapseFive" class="panel-collapse collapse in" role="tabpanel" aria-labelledby="headingFive">
            <div class="panel-body">
              Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird
              on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table,
              raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
            </div>
          </div>
        </div>
        <div class="panel panel-default">
          <div class="panel-heading" role="tab" id="headingSix">
            <h4 class="panel-title">
              <a class="collapsed" role="button" data-toggle="collapse" data-parent="#accordion" href="#collapseSix" aria-expanded="true" aria-controls="collapseSix">
                Collapsible Group Item #6
              </a>
            </h4>
          </div>
          <div id="collapseSix" class="panel-collapse collapse in" role="tabpanel" aria-labelledby="headingSix">
            <div class="panel-body">
              Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird
              on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table,
              raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
            </div>
          </div>
        </div>
        <div class="panel panel-default">
          <div class="panel-heading" role="tab" id="headingSeven">
            <h4 class="panel-title">
              <a class="collapsed" role="button" data-toggle="collapse" data-parent="#accordion" href="#collapseSeven" aria-expanded="true" aria-controls="collapseSeven">
                Collapsible Group Item #7
              </a>
            </h4>
          </div>
          <div id="collapseSeven" class="panel-collapse collapse in" role="tabpanel" aria-labelledby="headingSeven">
            <div class="panel-body">
              Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird
              on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table,
              raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
            </div>
          </div>
        </div>
      </div>
    </div>
  </body>

  <footer></footer>

  <script src="js/script.js"></script>
</html>

【问题讨论】:

  • BContactUsCustomerContactUs 的代码似乎增加了额外的复杂性,这对于帮助找到答案是不必要的。该错误应该在 $(document).ready 回调或 API 使用的逻辑中
  • 请仔细检查$(aId + ' .panel-collapse:not(".in")').collapse('show');中的逻辑你可能已经否定了更多你想要的东西!
  • @Ricardo - 我已经检查过了。这不是问题 - 如果我将 JS ($(document).ready - 用于折叠/展开) 分开并放入不同的文件,一切正常,但这违背了目的。如何将其作为函数添加到具有“BContactUs”和“CustomerContactUs”的命名空间中,您认为这可能是解决方案吗?
  • 哦,这听起来像是script 加载问题。你能在&lt;/body&gt;之前试试putting jQuery吗?

标签: javascript html jquery twitter-bootstrap accordion


【解决方案1】:

这听起来像是 script 加载问题。您可以在 HTML 内容之后、&lt;/body&gt; 之前尝试moving jQuery 吗?

这样的事情可能会解决它:

HTML

<!doctype html>
<html lang="en">

  <head>
    <!--  Metadata, Stylesheets, Favicons, etc... -->
    <!-- ... -->    
  </head>

  <body>
    <!-- Content to create the initial DOM Tree-->
    <div class="extrainfo_outerbackground">
       <!-- ... -->
    </div>

    <!-- Scripts that manipulate the previously created DOM elements -->
    <!-- Double check order -->
    <script type="text/javascript" src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
    <!-- ... -->
    <script src="js/script.js"></script>
  </body>

</html>

【讨论】:

  • 试一试,但没有任何区别。同样的问题仍然存在。还有其他想法吗?
  • 我这么说是因为您提到它在将内容移出 HTML 时会起作用。很抱歉,它没有帮助,但它可能是一种变体。您能否将您的代码发布到codepen.io 之类的在线工具中,这可能有助于让更多人研究它并尝试解决它?
  • 谢谢。我已经抛出了 JS Fiddle 的链接,如果有人可以提供帮助,非常感谢!
  • API DOCS.in 类中没有提及我们。你能把它从 HTML 和 JS 代码中删除吗??
【解决方案2】:

API DOCS 没有提到使用 .in 类。所以我相信它不是 API 的一部分(仅供内部使用?)

代替

 <div id="collapseOne" class="panel-collapse collapse in" role="tabpanel" aria-labelledby="headingOne">          

尽量不要为所有DIV.panel-collapse添加in类:

 <div id="collapseOne" class="panel-collapse collapse" role="tabpanel" aria-labelledby="headingOne">

然后,以下任何程序调用都会按预期工作:

$(aId + ' .panel-collapse').collapse('show');
$(aId + ' .panel-collapse').collapse('hide');
$(aId + ' .panel-collapse').collapse('toggle');

您还需要查看代码的其他部分,但这会给您一个想法。

例如使用 show 类而不是 in 来读取状态:

numPanelOpen = $(accordionId + ' .collapse.show').length;

这里是一个工作版本(如果满足您的所有要求,您需要进行调整) https://jsfiddle.net/0syhjnpk/

【讨论】:

  • 谢谢,但这并没有什么不同。正如独立提到的,它工作正常。
  • 在你的 JSFiddle 上编辑后它对我有用
  • 您的解决方案的问题是,当您尝试单独打开标题时,一次只会打开一个标题,例如,如果我想阅读 #1 然后 #3 只有后者会展开,但是#1 会在我打开时自动折叠。
  • 关于加载中的不同行为,也许您可​​以创建一个单独的问题,显示 JSFiddles 中的工作代码和非工作代码以进行比较。您可以通过删除所有不必要的细节来进一步简化示例(例如,只有 3 个项目与原来的 7 个项目)。一旦您着手删除与您的特定问题无关的代码,您可能会意外找到答案 - 啊哈,这就是导致问题的代码!
  • 这真的很有帮助,感谢您为此付出的时间。
猜你喜欢
  • 2011-06-25
  • 2017-09-29
  • 2018-05-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-15
相关资源
最近更新 更多