one

How to change classes on click

I have a structure:

<table style="width: 100%;">
    <tr>
        <td>
            <a href="#" class="yy">one</a>
        </td>

    </tr>
    <tr>
        <td>
            <a href="#" class="xx">Two</a>
        </td>

    </tr>
    <tr>
        <td>
            <a href="#" class="xx">Three</a>
        </td>

    </tr>
</table>

CSS

.xx {
    border: 5px solid green;    
}

.yy {
    border: 5px solid red;    
}

now when clicked, the <a>class should change. those. if it is "xx", then it should be "yy" and vice versa, and the remainder <a>should remain as it is, I tried something like (ref: how to change the <> tag class in jquery )

$("a.xx").click(function() {
  $(".yy").not(this).removeClass("yy");
  $(this).toggleClass("yy");
});​

but it didn’t work that way, I tried to configure the code, but it doesn’t work. Can someone help.

EDIT: Maybe my question was not clear enough: if I click on the second <a>/ any other <a>then it will turn red and the rest of the tag should be green.ie if it <a>is red then it should turn green and the rest should be red and vice versa.

EDIT ( sje397): , xx/yy , , , xx, yy, u , xx. -

+3
2
$("a").click(function() {
  $(this).toggleClass("yy").toggleClass("xx");
});​

EDIT (- )

(.. "yy" ), "xx", :

$("a").click(function() {
  var $this = $(this); // this is just for performance
  if(!$this.hasClass('yy'))
    $('.yy').toggleClass("yy").toggleClass("xx");
  $this.toggleClass("yy").toggleClass("xx");
});​

, , cascading css . , . CSS, , . , CSS:

.xx {
    border: 5px solid green;    
}

.xx.yy {
    border: 5px solid red;    
}

"yy" "xx".

+21

.

, :

$("a.xx, a.yy").click(function() {
    var $this = $(this);
    if ($this.hasClass("xx")) {
         $this.removeClass("xx").addClass("yy");
    }
    else {
         $this.removeClass("yy").addClass("xx");
    }
});

: http://jsbin.com/ecidi3

(), :

$("a.xx, a.yy").click(function() {
    var $this = $(this);
    var classes = $this.hasClass("xx") ? ["xx", "yy"] : ["yy", "xx"];
    $this.removeClass(classes[0]).addClass(classes[1]);
});

, live:

$("a.xx, a.yy").live("click", function() {
    var $this = $(this);
    if ($this.hasClass("xx")) {
         $this.removeClass("xx").addClass("yy");
    }
    else {
         $this.removeClass("yy").addClass("xx");
    }
});

: http://jsbin.com/ecidi3/2 , , . , , , (), , .


, , . :

$("a.xx, a.yy").click(function() {
  var $this, c;
  $this = $(this);
  c = $this.hasClass("xx")
            ? {us: "yy", them: "xx" }
            : {us: "xx", them: "yy" };
   $("a." + c.us).removeClass(c.us).addClass(c.them);
   $this.removeClass(c.them).addClass(c.us);
});

http://jsbin.com/ecidi3/5

, , live, :

$("a.xx, a.yy").live("click", function() {
             // ^-- change here

: http://jsbin.com/ecidi3/6

+4

Source: https://habr.com/ru/post/1766215/


All Articles