jquery: click on a P, its color changes, click on another p, it's color changes. when clicking 2nd P, change the first P color?
i'm trying to access the previo开发者_如何学运维usly clicked paragraph/element. The user will click a paragraph, and the bg-color changes from white to blue, visually what this means for the user is that the P they clicked is now selected. When they click on a different paragraph, the previously selected paragraph's bg-color changes from blue back to white.
Is there a way to select the previously clicked paragraph? preferably without adding and removing classes. Obviously my code below doesn't work, but i've explained how I think the answer might work?
$('p').bind('click', function () {
//checks if an item was previously selected, if so, sets background back to white
$(previouslySelected).css({'backgroundColor':'white'})
//change the current background blue, then store this item for the next click
$(this).css({'backgroundColor':'blue'})
var previouslySelected = $(this)
})
Without classes, you'll need to store the variable outside the click handler function scope:
// on page load + wrapped in another function to avoid polluting global namespace
$(document).ready(function() {
var previouslySelected
$('p').bind('click', function () {
//checks if an item was previously selected, if so, sets background back to white
$(previouslySelected).css({'backgroundColor':'white'})
//change the current background blue, then store this item for the next click
$(this).css({'backgroundColor':'blue'})
previouslySelected = $(this)
})
})
Adding classes is a lot simpler though:
$('p').bind('click', function () {
$("p.selected").removeClass("selected")
$(this).addClass("selected")
})
css
.highlight
{
background-color:yellow;
}
html
<p class="highlightable"></p>
<p class="highlightable"></p>
<p class="highlightable"></p>
Javascript
jQuery(function(){
jQuery('.highlightable').bind('click',function(){
var elm=jQuery(this);
if(elm.hasClass('highlight'))
{
elm.removeClass('highlight')
}
else
{
jQuery('.highlight').removeClass('highlight');
elm.addClass('highlight');
}
});
});
DEMO
精彩评论