0

我编写了以下一小段 javascript(基于出色的parseURI函数)来识别用户的来源。我是 Javascript 新手,虽然下面的代码有效,但想知道是否有更有效的方法来实现同样的结果?

try {
        var path = parseUri(window.location).path;

        var host = parseUri(document.referrer).host;
        if (host == '') {
                alert('no referrer');
                }

        else if (host.search(/google/) != -1 || host.search(/bing/) != -1 || host.search(/yahoo/) != -1) {
                alert('Search Engine');
                }
        else {
                alert('other');
                }
        } 

catch(err) {}
4

2 回答 2

2

您可以使用替代搜索来简化主机检查:

else if (host.search(/google|bing|yahoo/) != -1 {

在为您的“无推荐人”错误提取主机之前,我也很想测试文档推荐人。

(我没有测试过这个)。

于 2011-03-09T14:33:16.683 回答
0

我最终定义了一个set在我的很多项目中调用的函数。它看起来像这样:

function set() {
    var result = {};
    for (var i = 0; i < arguments.length; i++)
        result[arguments[i]] = true;
    return result;
}

一旦你得到你正在寻找的主机名部分......

// low-fi way to grab the domain name without a regex; this assumes that the
// value before the final "." is the name that you want, so this doesn't work
// with .co.uk domains, for example
var domain = parseUri(document.referrer).host.split(".").slice(-2, 1)[0];

in...您可以使用 JavaScript 的运算符和set我们在上面定义的函数优雅地针对列表测试您的结果:

if (domain in set("google", "bing", "yahoo"))
    // do stuff

更多信息:

于 2011-03-09T16:03:57.470 回答