如何使用jquery从数组中查找单击元素的索引?

时间:2012-02-04 22:42:02

标签: javascript jquery

如何使用jquery ???

从数组中找到单击的锚标记的索引

我想搜索是否存在eqqal点击元素的元素,如果为true则返回该元素的索引。

我尝试了类似的东西,但它返回-1

$('#id').click(function(){

var obj = $('a').get(0).href;
var arr = $.makeArray(obj);
var getclickedhref = $(this).get(0).href;

var clickedindex = $.inArray(getclickedhref, arr);

console.log(clickedindex);
});
你能帮助我吗??!

2 个答案:

答案 0 :(得分:10)

我不确定所有getmakeArray内容是什么,但我认为您正在寻找index

  

从匹配的元素中搜索给定元素。

所以给了一些锚点:

<a>Zero</a>
<a>One</a>
<a>Two</a>
<a>Three</a>
<a>Four</a>
你可以这样做:

$('a').click(function() {
    var i = $('a').index(this);
    // i is the index of the clicked anchor within all the anchors.
});

演示:http://jsfiddle.net/ambiguous/YbUU7/

答案 1 :(得分:2)

这个怎么样:

$('a').click(function(){
console.log($(this).index());
})