The best and fastest way to switch elements style in jQuery?
Adding currentSelected
class when I click the item, and removing the previously-selected item's currentSelected
class if I select another item. And remove currentSelected
class when I click outside of the item list.
<ul&g开发者_高级运维t;
<li class="dataItem currentSelected">item 1</li>
<li class="dataItem"> item 2</li>
<li class="dataItem"> item 3</li>
<li class="dataItem"> item 4</li>
</ul>
<ul id="myul">
<li class="dataItem currentSelected">item 1</li>
<li class="dataItem"> item 2</li>
<li class="dataItem"> item 3</li>
<li class="dataItem"> item 4</li>
</ul>
.
$('#myul li.dataItem').click(function(e){
$(this).addClass('currentSelected')
.siblings('.currentSelected')
.removeClass('currentSelected');
e.stopPropagation();
});
$(document).click(function(){
$('.currentSelected')
.removeClass('currentSelected');
});
demo
It's easiest to handle everything at the document level, so that the logic of adding and removing classes can be combined into one handler, and there's no need to unecessarily block event propagation.
$(document).click(function(e) {
$('li.dataItem').removeClass('currentSelected');
$(e.target).closest('li.dataItem').addClass('currentSelected');
});
If the click didn't come from an li.dataItem
, then $(e.target).closest('li.dataItem')
will return an empty jQuery object, and addClass
will have no effect.
$('li').click(function(){
$('.currentSelected').removeClass('currentSelected');
$(this).addClass('currentSelected');
};
What you can do, is store a variable which will hold the last item selected, so you can slip the first css-class selector.
var lastItem;
$('li').click(function(){
if(lastItem) {
lastItem.removeClass('currentSelected');
}
lastItem = $(this).addClass('currentSelected');
};
精彩评论