I'm trying to delegate click event to all first ancho开发者_JAVA技巧r tags of all now and future divs with "panels" class. I did something like that:
$('#panel').delegate('.panels a:first', 'click', function(event) [...]
but that doesn't work. It binds event only to one, first ".panels". Any hints?
I don't think you can do this just with a selector, unless it happens that the a
elements are not just the first anchor, but the first child of any kind inside the "panels" div
s (in which case you can use :first-child
).
You'll probably have to put some logic in the handler itself, to check that the anchor clicked is the first anchor in the div
. Something along these lines:
$("#panel").delegate(".panels a", "click", function() {
if ($(this).siblings("a").andSelf()[0] === this) {
// It's the first anchor in its parent
}
return false;
});
Live example
That works because siblings
and andSelf
both guarantee to keep the array inside the jQuery object in document order, so checking if this
is the [0]
th element works.
You want to use :first-child
, :first
only returns one element.
What you are doing now is equal to $('.panels a').get(0)
Source:
http://api.jquery.com/first-selector/
精彩评论