开发者

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?

开发者 https://www.devze.com 2023-02-15 18:42 出处:网络
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

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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号