忽略文件扩展名jQuery之后的查询字符串

Ignore a query string after a file extension jQuery

本文关键字:查询 字符串 之后 jQuery 文件 扩展名      更新时间:2023-12-05

我正在使用一个在这里找到的脚本:http://www.blastam.com/blog/index.php/2011/04/how-to-track-downloads-in-google-analytics/将Google分析跟踪代码动态添加到指向PDF文档的链接中。

我已经实现了它,并意识到这个网站中的PDF文档都有一个附加在URL末尾的查询字符串。不幸的是,由于查询字符串的原因,该脚本无法将文档识别为PDF。我需要修改这个脚本以忽略.pdf文件扩展名后的查询字符串,但我在这样做时遇到了问题。下面是我稍微修改过的脚本:

var filetypes = /'.(pdf?)$/i;
var baseHref = '';
if (jQuery('base').attr('href') != undefined)
        baseHref = jQuery('base').attr('href');
    jQuery('a').each(function() {
        var href = jQuery(this).attr('href');
        if (href && (href.match(/^https?':/i)) && (!href.match(document.domain))) {
            jQuery(this).click(function() {
                var extLink = href.replace(/^https?':'/'//i, '');
                _gaq.push(['_trackEvent', 'External', 'Click', extLink]);
                if (jQuery(this).attr('target') != undefined && jQuery(this).attr('target').toLowerCase() != '_blank') {
                    setTimeout(function() { location.href = href; }, 200);
                    return false;
                }
            });
        }
        else if (href && href.match(filetypes)) {
            jQuery(this).click(function() {
                var extension = (/[.]/.exec(href)) ? /[^.]+$/.exec(href) : undefined;
                var filePath = href;
                _gaq.push(['_trackEvent', 'Download', 'Click-' + extension, filePath]);
                if (jQuery(this).attr('target') != undefined && jQuery(this).attr('target').toLowerCase() != '_blank') {
                    setTimeout(function() { location.href = baseHref + href; }, 200);
                    return false;
            }
        });
    }
});

解析URL并在找到.pdf扩展名后停止的最佳方法是什么?

要在查找文件扩展名之前删除查询字符串,可以更改以下内容:

 var extension = (/[.]/.exec(href)) ? /[^.]+$/.exec(href) : undefined;
 var filePath = href;

到此:

 var fname = href;
 var query = href.indexOf("?");
 if (query !== -1) {
     fname = href.substr(0, query);
 }
 var extension = (/[.]/.exec(fname)) ? /[^.]+$/.exec(fname) : undefined;
 var filePath = fname;

工作演示:http://jsfiddle.net/jfriend00/JV78r/