使用jQuery检查链接是内部还是外部 [英] Using jQuery to check if a link is internal or external

查看:68
本文介绍了使用jQuery检查链接是内部还是外部的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想写一个脚本来确定链接是内部的还是外部的.从我的角度来看,这很简单,所有内部链接都是相对的,因此它们以/开头.所有外部链接均以http://开头-到目前为止一切正常.但是我不知道如何对文本以外的其他东西执行':contains()'-如何在属性内搜索字符串?

I want to write a script which can determine whether a link is internal or external. This is simple from my perspective, all internal links are relative, so they start with a /. All external links start with an http:// - all good so far. However I can't figure out how to do a ':contains()' on anything other than text - how can a search for a string within an attribute?

一旦我能做到这一点,我很乐意自己添加目标_blank,除非您知道一种更好的方法

Once I can do this I'm happy to add target _blank myself, unless you know a better way to do it

推荐答案

您可以使用 语法以查找以http/开头的hrefs:

You could use the attribute^=value syntax to find hrefs that start with http or /:

$("a[href^='http']") // external

$("a[href^='/']") // internal


这是一个更好的解决方案:您可以使用下面的插件代码将$('a:external')$('a:internal')选择器添加到jQuery.任何以http://https://whatever://开头的URL都被视为外部URL.


Here's a better solution: You can add $('a:external') and $('a:internal') selectors to jQuery with the plugin code below. Any URL that begins http://, https://, or whatever:// is considered external.

    $.expr[':'].external = function (a) {
        var PATTERN_FOR_EXTERNAL_URLS = /^(\w+:)?\/\//;
        var href = $(a).attr('href');
        return href !== undefined && href.search(PATTERN_FOR_EXTERNAL_URLS) !== -1;
    };

    $.expr[':'].internal = function (a) {
        return $(a).attr('href') !== undefined && !$.expr[':'].external(a);
    };

这篇关于使用jQuery检查链接是内部还是外部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆