简体   繁体   中英

jQuery - Change CSS of one element from many with same class identification

I am working around a simple jQuery script that is changing the backgroud color of an element when clicked.

Here is my code:

<script src="//code.jquery.com/jquery-1.10.2.js"></script>

<div class="radio">Text1</div>
<div class="radio">Text2</div>
<div class="radio">Text3</div>
<div class="radio">Text4</div>

I want the following to happen:

I click on "Text1" and this div is changing his background color to red and stay red.

I click on "Text2" and the background color of "Text1" is going back to white and then the background color of "Text2" is going and stay red.

I hope i give you a good description.

Can you help me make it ?

Thanks in advance!

 $('.radio').click(function(){ $('.red').removeClass('red'); $(this).addClass('red'); }); 
 .red{ background-color: red; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <div class="radio">Text1</div> <div class="radio">Text2</div> <div class="radio">Text3</div> <div class="radio">Text4</div> 

Here is a way to do it with pure CSS:

 input { display: none; } label { display: block; } input:checked + label { background-color: red; } 
 <input id="text1" type="radio" name="g1"> <label for="text1">Text1</label> <input id="text2" type="radio" name="g1"> <label for="text2">Text2</label> <input id="text3" type="radio" name="g1"> <label for="text3">Text3</label> <input id="text4" type="radio" name="g1"> <label for="text4">Text4</label> 

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