检查页面上是否已存在链接

时间:2022-04-03 04:28:04

I'm trying to solve for two scenarios:

我正在尝试解决两种情况:

  1. Identify if the link clicked exists already on the page.

    确定点击链接是否已存在于页面上。

  2. Then if the link already exists, get the index() for the link clicked of the duplicate links.

    然后,如果链接已存在,请获取单击链接的链接的index()。

My code is not working correctly since it's not identifying correctly if the link clicked is a duplicate and it's giving me an index of the sum of all links instead of the duplicate link.

我的代码无法正常工作,因为如果点击的链接是重复的,并且它给了我所有链接总和而不是重复链接的索引,则它无法正确识别。

$("a").click(function() {
   Rank = $(this).index('a');
   if($("a").attr("href") != $(this).attr("href")) {
        alert('\nLink Rank '+Rank+'\n\nYes, this is duplicate link');
       return false;
    }
    else {
        alert('\nLink Rank '+Rank+'\n\nNo, this is NOT a duplicate link');
        return false;
    }
});

Demo: http://jsfiddle.net/no4gkk0n/1/

1 个解决方案

#1


You can look for elements with the same attribute with the attribute selector: [href="foo"], then check the length property. If it's more than 1, there is a duplicate link:

您可以使用属性选择器查找具有相同属性的元素:[href =“foo”],然后检查length属性。如果它超过1,则存在重复链接:

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

Example fiddle

#1


You can look for elements with the same attribute with the attribute selector: [href="foo"], then check the length property. If it's more than 1, there is a duplicate link:

您可以使用属性选择器查找具有相同属性的元素:[href =“foo”],然后检查length属性。如果它超过1,则存在重复链接:

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

Example fiddle