简体   繁体   中英

jQuery delegate selector problem

I'm trying to delegate click event to all first anchor 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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM