make the first element style's be removed when next element is clicked
This question answered part of what I wanted to do except that when the page first loaded, I can't get the result for the first element and have it removed when the second element is clicked.
<li><a href="#">first elemen开发者_开发知识库t</a></li>
<li><a href="#">second element</a></li>
<li><a href="#">third element</a></li>
li a {
border: 1px solid blue
}
.selected {
border-color: red
}
When the page first loaded, the first element is not clicked and I want it to show the red border color (selected), but when second element is clicked, the red color should be replaced with blue,.
Just add:
$(function() {
var $lia = $('li').find('a');
$lia.click(function(e) {
$lia.removeClass('selected');
$(this).addClass('selected');
});
$lia.first().addClass('selected');
});
Here's an example!
HTML:
<ul class="options">
<li class="selected"><a href="#">first element</a></li>
<li><a href="#">second element</a></li>
<li><a href="#">third element</a></li>
</ul>
JavaScript:
$(function() {
$('ul.options').delegate('li a', 'click', function() {
$('li.selected').removeClass('selected');
$(this).addClass('selected');
});
});
You don't need to add the class to he first element with JavaScript it it always has to be there when the page loads, and this will work also if new li
are added dynamically.
精彩评论