我有一个覆盖链接行为的 jQuery 插件,以允许 Ajax 加载页面内容。使用 $(document).on('click','a', function(){});
这样的委托(delegate)事件就足够简单了。
但是我只希望它应用于与这些链接不同的链接(Ajax 加载不适用于它们,因此这些链接需要正常运行):
target="_blank" // New browser window
target="_self" // Force replacement of current window (specific to my plugins)
href="#..." // Bookmark link (page is already loaded).
href="afs://..." // AFS file access.
href="cid://..." // Content identifiers for MIME body part.
href="file://..." // Specifies the address of a file from the locally accessible drive.
href="ftp://..." // Uses Internet File Transfer Protocol (FTP) to retrieve a file.
href="http://..." // The most commonly used access method.
href="https://..." // Provide some level of security of transmission
href="mailto://..." // Opens an email program.
href="mid://..." // The message identifier for email.
href="news://..." // Usenet newsgroup.
href="x-exec://..." // Executable program.
href="http://AnythingNotHere.com" // External links
示例代码:
$(document).on('click', 'a:not([target="_blank"])', function(){
var $this = $(this);
if ('some additional check of href'){
// Do ajax load and stop default behaviour
return false;
}
// allow link to work normally
});
问:
有没有办法轻松检测所有只能在当前网站内导航的“本地链接”?排除上述所有变体。
注意:这是针对 MVC 5 Razor 网站的,因此不太可能出现绝对站点 URL。
最佳答案
我可能会使用选择器:
$('a:not([href*="://"],[target="_blank"],[href^="#"],[href^="mailto:"])')
http://jsfiddle.net/mblase75/Pavg2/
请注意,mailto:
是正确的,而不是您原始问题中的 mailto://
。
为了完整起见,以下还将捕获使用绝对 URL 的内部链接 (http://the-domain-you-are-on-now.com/whatever.html
) :
$('a:not([href*="://"],[target="_blank"],[href^="#"],[href^="mailto:"]),a[href^="'+location.protocol+'//'+location.hostname+'"]')
关于javascript - RegEx 表达式或 jQuery 选择器不匹配 href 中的 "external"链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24084627/