jQuery添加和删除父类以创建手风琴

时间:2018-06-28 11:15:45

标签: jquery html css

我想在单击按钮时将clickElementGeneralDivProducts类设置为nowCollapse或Now折叠类。 您已经做过这样的事情吗? 预先感谢

这是我的html:

    <div class="row viewElementGeneraleDivProdotti nowcollapse">
          <button class="accordionType">
              <div class="openclose accordion-header viewNomeProdottoSingolo nowcollapse">Master Frit</div>
            <div class="viewIconRightPlus">
              <div class="toggle-plus">
                    <span></span>
                    <span></span>
                </div>
             </div>
          </button>
          <div class="openclose accordion-content panel-collapse nowcollapse">
            <div class="viewImageAndDescription">
              <div class="viewImmagineProdottoSingolo"><img src="http://xxxxxxxxxxxx/wp-content/uploads/2018/06/59INBIIVpr1GukNtJs-wpcf_210x300.jpg" title="59INBIIVpr1GukNtJs" class="attachment-medium"></div>
              <div class="viewDescrizioneProdotto"><p>Olio di palma frazionato, ideale per fritture e con punto di fumo ˃ 220°</p>
</div></div></div></div> 

这是我的jquery:

jQuery('.accordionType').on('click', function() {
 if (jQuery('.viewElementGeneraleDivProdotti').hasClass(".nowcollapse")) {
   $('.viewElementGeneraleDivProdotti').removeClass(".nowcollapse");
$('.viewElementGeneraleDivProdotti').addClass(".nowcollapsed");
  }
  else
  {
   $('.viewElementGeneraleDivProdotti').removeClass(".nowcollapse");
$('.viewElementGeneraleDivProdotti').addClass(".nowcollapsed");
  }
});

1 个答案:

答案 0 :(得分:0)

在检查,删除类并将其添加到元素时,从className中删除..仅在按元素类名称选择元素时使用。

$('.accordionType').on('click', function() {
    const parent = $(this).parents('.viewElementGeneraleDivProdotti');
    if(parent.hasClass('nowcollapse')) {
        parent.removeClass('nowcollapse').addClass('nowcollapsed')
    } else {
        parent.removeClass('nowcollapsed').addClass('nowcollapse')
    }
});

$('.accordionType').on('click', function() {
        const parent = $(this).parents('.viewElementGeneraleDivProdotti');
        if(parent.hasClass('nowcollapse')) {
            parent.removeClass('nowcollapse').addClass('nowcollapsed')
        } else {
            parent.removeClass('nowcollapsed').addClass('nowcollapse')
        }
    });
.nowcollapse .content {display: none;}
.nowcollapsed .content {display:block;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row viewElementGeneraleDivProdotti nowcollapse">
          <button class="accordionType">Toggle
          </button>
          <div class="content">Content here</div>
</div>