开发者

How to click and "unclick" an element

开发者 https://www.devze.com 2023-04-06 02:10 出处:网络
Okay, I\'m a real beginner when it comes to jQuery, and although I\'ve tried searching for this alread开发者_高级运维y, I can\'t seem to find an answer (I\'m probably not phrasing it correctly).

Okay, I'm a real beginner when it comes to jQuery, and although I've tried searching for this alread开发者_高级运维y, I can't seem to find an answer (I'm probably not phrasing it correctly).

When one of the li's are clicked, I want to add an element. However, if the li has already been clicked (and the class already added), if the user clicks again, I want the class removed. So far, this is what I have:

(function($){ 
   $(".list li").click(function() {
      $(this).addClass("hilite");
      $(this).attr("BeenClicked", "true");
   });
 })(jQuery); 

<ul class="list">
   <li> Something
   <li> Something else
</ul>

I need to create code that essentially checks the attribute to see if "BeenClicked" is set to true.


You'll have to use jQuery's toggleClass:

(function($){ 
   $(".list li").click(function() {
      $(this).toggleClass("hilite");
   });
})(jQuery);


Use .toggleClass() to automatically alternate the class on each click:

(function($){ 
   $(".list li").click(function() {
      $(this).toggleClass("hilite");
   });
 })(jQuery); 

<ul class="list">
   <li> Something
   <li> Something else
</ul>

There's no need to separately store the "BeenClicked" attribute. You can see if it has the class on it at any time with the .hasClass("hilite") method.

In addition, if you were going to store data on it, then the jQuery way would be with the .data() method: $(this).data("BeenClicked", true);.


You might want to check out jQuery's toggleClass() method.

http://api.jquery.com/toggleClass/

Just call it in your click handler.

0

精彩评论

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