jquery click event handler for items within a div
How do you add a jquery click event handler for a bunch of links within a div? For e开发者_如何转开发xample:
<div class="test">
<a href="test1.html">link 1</a>
<a href="test2.html">link 2</a>
<a href="test3.html">link 3</a>
</div>
I'd like to add a click event handler for each of the three links, so I can addClass('selected') to the link that was clicked on and removeClass('selected') from the rest.
I know I can do them one by one, but I was wondering what the cleanest way to do this is...
I would use .delegate()
:
var classname = 'selected';
$('div.test').delegate('a', 'click', function ()
{
$(this).addClass(classname).siblings().removeClass(classname);
});
The selector will return an array of elements that match.
$('div.test a')
will be the tree links.
$('div.test a').click(function() { });
Will bind to all three.
Selectors work like CSS selectors, so this selects a
tags inside tags with class test
$('.test a').click(function(){
// select the object that was clicked on
$(this)
// add the selected class to it
.addClass('selected')
// remove the selected class from it's brothers and sisters
.siblings().removeClass('selected')
// stop link from loading and resetting page
return false
})
Demo here: http://jsfiddle.net/HK6CE/
I would write (with no extra markup):
$('.test a').bind('click', function() {
$(this).addClass('selected').siblings().removeClass('selected');
});
Siblings() gets all the others dom elements on the same level, so it'll get all the others "a" inside .test
I believe it's $('.test').each(function(){})
精彩评论