我正在使用以下 jQuery 代码来选择所有内部链接...
var siteURL = "http://" + top.location.host.toString();
var $internalLinks = $("a[href^='"+siteURL+"'], a[href^='/'], a[href^='./'], a[href^='../'], a[href^='#']");
而且效果很好。我面临的唯一问题是我不想选择直接指向可下载文件的内部链接(例如 http://www.example.com/downloadable.pdf )
扩展名可以是任何内容(pdf、mp3、jpg、gif、webm ...等)
现在的问题是,如何从上述条件中排除此类内部链接?
或者,如果我使用 .not() 函数来排除此类链接,问题是,如何选择直接指向此类可下载文件的所有内部链接?
最佳答案
一个简单的解决方案是使用filter
或not
与正则表达式来拒绝您不想要的链接:
var $internalLinks = $("a[href^='"+siteURL+"'], a[href^='/'], a[href^='./'], a[href^='../'], a[href^='#']");
$internalLinks = $internalLinks.not(function () {
return $(this).attr('href').match(/\.(pdf|mp3|jpg|jpeg|etc)$/i);
});
相反,假设所有“不可下载”的网址都以 .html
或 .htm
结尾,则会过滤
链接带有这些扩展:
$internalLinks = $internalLinks.filter(function () {
return $(this).attr('href').match(/\.html?/);
});
关于jQuery:选择所有内部链接,不包括可下载文件的链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23702816/