获取每组重复链接的索引

时间:2015-05-18 19:29:13

标签: jquery

当页面上存在一组像amazon.com或google.com(等)的链接时,它将被多次列出。我试图找到每组重复链接的索引。

这就是我所期待的:

  • 例如。 amazon.com(索引0)
  • 例如。 amazon.com(索引1)
  • 例如。 amazon.com(索引3)
  • 例如。 google.com(索引0)
  • 例如。 google.com(索引1)

但是,我没有通过此功能获得预期的结果:



$("a").click(function(e) {
  e.preventDefault();
  var $links = $("a[href='" + $(this).attr("href") + "']");
  var isDupe = $links.length > 1;
  if ($links.length > 1) {
    var rank = isDupe ? $links.not(this).index('a') : $(this).index('a');
    alert('\nLink Rank ' + rank + '\n\nYes, this is duplicate link');
  } else {
    alert('No, this is NOT a duplicate link');
  }
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<a href="http://www.google.com">Google</a> (Google is not a duplicate)
<BR>
<a href="http://www.intranet.com">Intranet</a> (Intranet is not duplicate)
<BR>
<BR>i want this to say index <strong>0</strong>, but it returns index 3
<BR>
<a href="http://www.example.com">Example</a> (Example is a duplicate)
<BR>
<BR>i want this to say index <strong>1</strong>, but it returns index 2
<BR>
<a href="http://www.example.com">Example</a> (Example is a duplicate)
<BR>
<BR>i want this to say index <strong>0</strong>, but it returns index 5
<BR>
<a href="http://www.amazon.com">Amazon</a> (Amazon is a duplicate)
<BR>
<BR>i want this to say index <strong>1</strong>, but it returns index 4
<BR>
<a href="http://www.amazon.com">Amazon</a> (Amazon is a duplicate)
<BR>
<BR>i want this to say index <strong>2</strong>, but it returns index 4
<BR>
<a href="http://www.amazon.com">Amazon</a> (Amazon is a duplicate)
<BR>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:2)

DEMO

var index = isDupe ? $links.not(this).index('a') : $(this).index('a');更改:

$links.not(this).index('a')

致:

$links.index(this)

不确定您是否需要$(this).index('a')部分,但如果您需要,则应该是:

$('a').index(this)