简体   繁体   中英

jQuery click more than once

I have started teaching myself jQuery and I was wondering how you can add multiple click functions where something different happens with each click.

Heres an example of what i am trying to do :

$(document).ready(function() {
$("#color").click( function() {
$("#change_me").css("color", "purple");
$("#change_me").css("color", "black");
});//end color
});//end doc ready

I originally only had the "purple" line so when I clicked on the text it changed purple. I then added the "black" line (to return it to the default colour) but it now bypasses the purple state.

I tried adding another click function but that didn't work

You can use jQuery toggleClass for that, create a class with the color you want after click and on click it will add/remove the class

 $(document).ready(function() { $("#color").click( function() { $("#change_me").toggleClass("purple"); //$("#change_me").css("color", "black"); });//end color });//end 
 .purple{ color:purple; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="color"> <p id="change_me"> Click on the text to change its color </p> </div> 

if you want to change between more than 2 colors you can do it like this

 $(document).ready(function(){ $("#change_me").toggle( function(){$("#change_me").css({"color": "purple"});}, function(){$("#change_me").css({"color": "black"});}, function(){$("#change_me").css({"color": "green"}); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script> <div id="color"> <p id="change_me"> Click on the text to change its color </p> </div> 

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