简体   繁体   中英

Getting ALL First links in a specific class

So I know that using "a:first" will get the first link of a page. Lets assume we have the following:

<div class="masterclass">
   <a href="#">Link 1</a>
   <a href="#">Link 2</a>
</div>
<div class="masterclass">
   <a href="#">Link 1</a>
   <a href="#">Link 2</a>
</div>

Naturally I can use the following code to get the first "a" of the class "masterclass"

$('.masterclass a:first').click(function() {
alert('yayfirstlink');
});

However I do not understand how to get the first link of every "masterclass"

You need to use find() here because your selector will find all the anchor elements with in .masterclass then filter only the very first one. But when you use .find() , it will find all the .masterclass elements first then will find the first anchor element in each of them.

$('.masterclass').find('a:first').click(function() {
alert('yayfirstlink');
});

or if you are sure that the target element will be the first child of its parent then you can use :first-child

$('.masterclass a:first-child').click(function() {
alert('yayfirstlink');
});

尝试这个,

var oFirstAnchor = $(".masterclass a:first-child");

$(".masterclass a:first-child") is what you are looking for.

so:

$('.masterclass a:first-child').click(function() {
    alert('yayfirstlink');
});

This is how u loop through each of the masterclass and get the first link of it. i don't know what you want to do with it though so i can only provide this

$(document).ready(function(){

var fields = $('.masterclass a:first-child');
  $.each(fields, function(index, val){
     alert(index);
  });
});

this alerts the current links array index http://jsfiddle.net/kBd82/6/

I would recommend using the first of type selector for this.

$('.masterclass a:first-of-type')

This way it will always select the first anchor tag in each masterclass div even if you put other things in the div later.

http://api.jquery.com/first-of-type-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