简体   繁体   中英

.click function, remove class after clicked

I have this function so if I click for example ITEM 1 , the sample1 and sample3 will become red because have that specific class ( class1 ).

The problem is that if I click on another item (for example ITEM2 ), the red items of ITEM1 will remain red and I need them to turn black and highlight in red ONLY the items of current clicked class in the first list.

What to add to below ready(function() in order to do that? Thank you in advance!

<ul>
    <li class="leftcol class1">ITEM 1</li>
    <li class="leftcol class2">ITEM 2</li>
    <li class="leftcol class3">ITEM 3</li>
    <li class="leftcol class4">ITEM 4</li>
</ul>

<ul>
    <li class="rightcol class1 class4">sample1</li>
    <li class="rightcol class2 class3">sample2</li>
    <li class="rightcol class3 class1">sample3</li>
    <li class="rightcol class4 class2">sample4</li>
</ul>

This is the function:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<script>
    $(document).ready(function() {
        $('.leftcol').click(function() {
            $('.rightcol[class*=' + this.className.split(" ").pop() + ']').css('color', 'red');    
        });
    });
</script>

Use classes to hold the styles, and then just remove the class on all elements, and add it back on the elements matching the class etc

 $(document).ready(function() { $('.leftcol').click(function() { $('.rightcol').removeClass('red') .filter('.'+ this.className.split(" ").pop()) .addClass('red'); }); }); 
 .red {color: red} 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul> <li class="leftcol class1">ITEM 1</li> <li class="leftcol class2">ITEM 2</li> <li class="leftcol class3">ITEM 3</li> <li class="leftcol class4">ITEM 4</li> </ul> <ul> <li class="rightcol class1 class4">sample1</li> <li class="rightcol class2 class3">sample2</li> <li class="rightcol class3 class1">sample3</li> <li class="rightcol class4 class2">sample4</li> </ul> 

Since you are not using class to style items, logic is this, on each click reset color of all items with class .rightcol and after reset add red to one u want. Try something like this:

 $(document).ready(function() {
 $('.leftcol').click(function() {
$('.rightcol').css('color', 'black');
$('.rightcol[class*=' + this.className.split(" ").pop() + ']').css('color',     'red');
});
});

Have you tried using a variable in which you store the name of the class that you last changed its color from? So whenever your function is called you can change the color back to default and update the variable. Another option would be to first set all classes colors to default and then execute the line to change the color to red.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM