开发者

Get the number of element or id when click?

开发者 https://www.devze.com 2023-02-16 06:30 出处:网络
I wonder if it\'s possible to get the number of a <a> tag when you click on it by using $this? Lets say I have a list of links and I want to get the number in the order it has inbetwen a div wit

I wonder if it's possible to get the number of a <a> tag when you click on it by using $this? Lets say I have a list of links and I want to get the number in the order it has inbetwen a div with a class name someLinks

<div class="someLinks">
 ...="#" id="开发者_如何学Go1">some text or an image</a>
 ...="#" id="2">some text or an image</a>
 ...="#" id="3">some text or an image</a>
</div>

(sorry but I could not include a tags)

Perhaps it could be done with some code like this $(".someLinks:eq(???? Or if there is some way to get the number of the ID when click on the <a> tag by using $this and perhaps attr?

Preciate some help! I'm new to jQuery so I want to keep the code simple. Thanks!


Not exactly sure what you mean by tag or the number of it, but if you're looking for an easy way to track a click on certain class names, you can do something like this:

$('.someLinks').click(function() {
    alert( $(this).attr('id') )
});


You use .index() -function to calculate the element index based on a list- combined with $(this) - the link being clicked -

$("a").click(function(){ //when a link is clicked
    var linkList = $(".someLinks").find("a"); //Get list of links inside div
    var index = linkList.index($(this))); //Search for this in the list
    alert(index); //alert
});

Online example: http://jsfiddle.net/7kvMF/1/


get the index of THIS element

$('.someLinks a').live('click',function(){
    alert($('.someLinks').index($(this)));

});


You can use .index(element) to get the position of one element in another selection, I.E:

var allLinks = $(".someLinks a");

allLinks.click(function(e) { 
  alert("You clicked on the "+(allLinks.index(this))+" a tag");
  e.preventDefault();
});

You also asked about getting the elements ID:

allLinks.click(function(e) {
  if (this.id) alert("The A tag you clicked on was #"+this.id);
});
0

精彩评论

暂无评论...
验证码 换一张
取 消