无法删除在按钮上动态添加的类

时间:2019-04-24 08:51:09

标签: javascript jquery

我向按钮添加了一个类,然后删除了当前类。现在,当我再次单击该按钮时,我想删除添加的类,然后添加旧的类。但它不起作用。似乎是什么问题?

HTML:

<div class="cost">
    <div class="for-cost-button">
        <button class="btn btn-success cost-button">Click Me</button>
    </div>
</div>

jQuery:

var j = jQuery.noConflict();
j(document).ready(function () {
    j(".cost-button").click(function () {
        j(".cost").addClass("show-cost");
        j(".cost-button").addClass("close-cost");
        j(".cost-button").removeClass("cost-button");
    });

    j(".for-cost-button").on("click", ".close-cost", function () {
        j(".cost").removeClass("show-cost");
        j(".close-cost").addClass("cost-button");
        j(".close-cost").removeClass("close-cost");
    });
});

1 个答案:

答案 0 :(得分:1)

这是您的代码出了什么问题:

您同时添加了两个事件侦听器,当您单击按钮时,您会自动单击按钮周围的div,这样会发生以下情况:

-您将类别show-cost添加到第一个div -您向按钮添加类别关闭费用 -您从按钮中删除课程费用按钮

  • show-cost类已从您的div中删除
  • 您将class show-cost添加到按钮.close-cost
  • 您从按钮中删除了班级关闭费用

如果您查看下面的注释代码

您会发现:

-1st动作撤消第4个动作,然后6th动作撤消第2个动作,然后5th动作撤消第3个动作

我已将console.log添加到您的代码中,以确保事件在单击按钮的同时发生

<div class="cost">
  <div class="for-cost-button">
      <button class="btn btn-success cost-button">Click Me</button>
 </div>
</div>
<script
  src="https://code.jquery.com/jquery-3.4.0.js"
  integrity="sha256-DYZMCC8HTC+QDr5QNaIcfR7VSPtcISykd+6eSmBW5qo="
  crossorigin="anonymous"></script>
<script>
var j = jQuery.noConflict();
j(document).ready( function () {
  j(".cost-button").click(function(){
    console.log(".cost-button is clicked");
     j( ".cost" ).addClass( "show-cost" ); // add a class to the first div
     j( ".cost-button" ).addClass( "close-cost" ); // add class close-cost to button
          j( ".cost-button" ).removeClass( "cost-button" ); // remove class cost-button from button
   });

   j(".for-cost-button").on("click", ".close-cost", function(){
     console.log("the div is clicked"); // when the div around the button is clicked
      j( ".cost" ).removeClass( "show-cost" ); // the class show-cost is removed from your div
      j( ".close-cost" ).addClass( "cost-button" ); // adds the class show-cost to the button .close-cost
      j( ".close-cost" ).removeClass( "close-cost" ); // removes the class close-cost from the button
   });
});
</script>