我见过很多jQuery示例,其中参数大小和名称都是未知的。

我的URL只会有一个字符串

http://example.com?sent=yes

我只想检测:

sent存在吗? 它等于"是"吗?


当前回答

试试这个工作演示http://jsfiddle.net/xy7cX/

火:

inArray: http://api.jquery.com/jQuery.inArray/

这应该会有帮助:)

code

var url = "http://myurl.com?sent=yes"

var pieces = url.split("?");
alert(pieces[1] + " ===== " + $.inArray("sent=yes", pieces));

其他回答

这将给你一个很好的工作对象

    function queryParameters () {
        var result = {};

        var params = window.location.search.split(/\?|\&/);

        params.forEach( function(it) {
            if (it) {
                var param = it.split("=");
                result[param[0]] = param[1];
            }
        });

        return result;
    }

然后;

    if (queryParameters().sent === 'yes') { .....

这里有一个很棒的图书馆: https://github.com/allmarkedup/purl

这能让你做得更简单

url = 'http://example.com?sent=yes';
sent = $.url(url).param('sent');
if (typeof sent != 'undefined') { // sent exists
   if (sent == 'yes') { // sent is equal to yes
     // ...
   }
}

这个例子假设您正在使用jQuery。你也可以使用它只是简单的javascript,语法会有点不同。

不可否认,我是在为一个过度回答的问题补充我的答案,但这有以下优点:

——不依赖于任何外部库,包括jQuery

—不污染全局函数名称空间,通过扩展'String'

—不创建任何全局数据,并在匹配后进行不必要的处理

处理编码问题,并接受(假设)非编码参数名

——避免显式的for循环

String.prototype.urlParamValue = function() {
    var desiredVal = null;
    var paramName = this.valueOf();
    window.location.search.substring(1).split('&').some(function(currentValue, _, _) {
        var nameVal = currentValue.split('=');
        if ( decodeURIComponent(nameVal[0]) === paramName ) {
            desiredVal = decodeURIComponent(nameVal[1]);
            return true;
        }
        return false;
    });
    return desiredVal;
};

然后你可以这样使用它:

var paramVal = "paramName".urlParamValue() // null if no match
http://example.com?sent=yes

最好的解决方案。

function getUrlParameter(name) {
    name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
    var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
    var results = regex.exec(location.href);
    return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, '    '));
};

使用上面的函数,你可以得到单独的参数值:

getUrlParameter('sent');

最好的解决方案。

var getUrlParameter = function getUrlParameter(sParam) {
    var sPageURL = window.location.search.substring(1),
        sURLVariables = sPageURL.split('&'),
        sParameterName,
        i;

    for (i = 0; i < sURLVariables.length; i++) {
        sParameterName = sURLVariables[i].split('=');

        if (sParameterName[0] === sParam) {
            return sParameterName[1] === undefined ? true : decodeURIComponent(sParameterName[1]);
        }
    }
    return false;
};

这就是你如何使用这个函数假设URL是, http://dummy.com/?technology=jquery&blog=jquerybyexample。

var tech = getUrlParameter('technology');
var blog = getUrlParameter('blog');