changing the bg color of an active click function in jquery?
开发者_运维知识库basically i have this click function in jquery: (this is just a snippet, not full)
$('.block').click(function(){
var id= $(this).attr('id');
i want to chnage the background color of the block that has been clicked only, assigned with the id i.e.
$('.block').click(function(){
var id= $(this).attr('id');
$('.block').css('background-color','grey');
but where do i assign the id, so jquery knows, to only turn the clicked block into grey, not the others, cheers
Using CSS classes are recommended. There are three methods toggleClass()
, addClass()
and removeClass()
$(".block").click(function() {
$('.block').removeClass('someClass');//remove the class for all items with class block
$(this).addClass('someClass');//add the class to the current one
});
See here for a working example. I answer your original question you would do this
$('.block').click(function(){
var id= this.id
$('#' + id).css('background-color','grey');
});
$('.block').click(function(){
$(this).css('background-color','grey');
});
when an element with class .block
is clicked, that specific element's background is set to grey.
working example: http://jsfiddle.net/Damien_at_SF/ZUE8x/
:)
To return the blocks to white you could do something like this:
$('.block').click(function(){
//set all blocks to white
$('.block').css('background-color','white');
//set the clicked block to grey
$(this).css('background-color','grey');
});
精彩评论