如何在jQuery中有条件地设置div的类?

时间:2023-01-13 17:54:50

CSS:

   #outer{
    background-color:#FFFF99;            
   }

   #inner1{
      float : left;
   }

    .New1{
      width: 62%; 
    }

   .New2{
     width: 72% 
   }

I need to be able to change the class of a div after a condition in an event handler.

我需要能够在事件处理程序中的条件之后更改div的类。

Logic:

         case '1': <div id="outer" class="New1"> 
                   </div>
         case '2': <div id="outer" class="New2">
                    </div>

To do this, I wrote the following jQuery:

为此,我编写了以下jQuery:

$("#generate").click(function(){
     // here I wrote code for case '1'
     $("#outer").addClass("New1");
});
$("#choice").click(function(){
     // here I wrote code for case '2'
     $("#outer").addClass("New2");
}); 
  • Do I need to remove the class that I previously added to it?

    我是否需要删除之前添加的类?

  • I need to toggle between two states.

    我需要在两个州之间切换。

How can I do this?

我怎样才能做到这一点?

1 个解决方案

#1


$("#generate").toggle(function() {
    $("#outer").removeClass("New2").addClass("New1");
}, function() {
    $("#outer").removeClass("New1").addClass("New2");
});

or

$("#generate").click(function() {
    $("#outer").removeClass("New2").addClass("New1");
});
$("#choice").click(function() {
    $("#outer").removeClass("New1").addClass("New2");
});

#1


$("#generate").toggle(function() {
    $("#outer").removeClass("New2").addClass("New1");
}, function() {
    $("#outer").removeClass("New1").addClass("New2");
});

or

$("#generate").click(function() {
    $("#outer").removeClass("New2").addClass("New1");
});
$("#choice").click(function() {
    $("#outer").removeClass("New1").addClass("New2");
});