1

请多多包涵。我正在尽力解释我需要什么,但我可能需要对我的 OP 进行一些更新。

我想获取所选元素在层次结构中的位置。例如,如果我在整个 html 文档中总共有 4 个超链接,并且我将鼠标悬停在第三个链接上,我想要“html > body > a:eq(2)” - 2 表示第三个超链接元素。

不,index()不成功。

我已经通过一些调整尝试了这段代码并得到了这个:“html > body > a”,但找不到返回位置的函数。

如何在相似元素的层次结构中获取所选元素的位置?(我什至不知道这是否是正确的术语。)如果 x==y 有点事情,我是否需要遍历 DOM 并执行手动匹配

<a href=#">link1</a> 
<a href=#">link2</a> 
<a href=#">link3</a> 
<a href=#">link4</a>

我将把这段代码用于各种 HTML 元素,而不仅仅是超链接。

4

3 回答 3

1

如果您有一个给定的元素并且想知道它在文档中的第 n 个链接,您可以这样做:

function whichLink(el) {
    return $("a").index(el);
}

这种形式.index(el)返回 jQuery 对象中的哪个项目与传入的元素匹配。它搜索 jQuery 对象以找到匹配的元素。由于 jQuery 对象按文档顺序对元素进行排序,这将为您提供给定链接在文档中的位置。

如果您尝试做一些不同的事情,请进一步澄清您的问题。

于 2012-06-05T19:13:51.787 回答
0

Since you want an action on hover I would suggest a slightly different approach. Instead of finding all the elements to get the index on every hover (which could happen quite often) event I would set the index when the document first loads so you can easily retrieve it when the event fires.

Something like:

$('a').each(function(i, el){            
    $(this).data('index', i); 
    $(this).hover(function(){
        var hoveredIndex = $(this).data('index');
        // Do you action with the index
    });
});

If you don't have much mark up or hovering doesn't happen often this might be overkill. Also if you have a container around the elements the selector/events could be revised.

于 2012-06-05T19:25:13.567 回答
0

通常,您可以在每个循环中执行此操作:

$('a').each(function(i) {
  // i has the index so we can do something with it
  var index = i;
  $(this).click(function() {
     $(this).attr('href', index);  // make the href = i for instance
  });
});
于 2012-06-05T19:09:58.803 回答