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

我的URL只会有一个字符串

http://example.com?sent=yes

我只想检测:

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


当前回答

2023年起的解决方案

我们有:http://example.com?sent=yes

let searchParams = new URLSearchParams(window.location.search)

sent存在吗?

searchParams.has('sent') // true

它等于"是"吗?

let param = searchParams.get('sent')

然后比较一下。

其他回答

我希望这能有所帮助。

 <script type="text/javascript">
   function getParameters() {
     var searchString = window.location.search.substring(1),
       params = searchString.split("&"),
       hash = {};

     if (searchString == "") return {};
     for (var i = 0; i < params.length; i++) {
       var val = params[i].split("=");
       hash[unescape(val[0])] = unescape(val[1]);
     }

     return hash;
   }

    $(window).load(function() {
      var param = getParameters();
      if (typeof param.sent !== "undefined") {
        // Do something.
      }
    });
</script>

试试这个工作演示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));
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');

2023年起的解决方案

我们有:http://example.com?sent=yes

let searchParams = new URLSearchParams(window.location.search)

sent存在吗?

searchParams.has('sent') // true

它等于"是"吗?

let param = searchParams.get('sent')

然后比较一下。

这个方法很简单,对我来说很管用

$.urlParam = function(name){
    var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
    return results[1] || 0;
}

如果你的url是http://www.yoursite.com?city=4

试试这个

console.log($.urlParam('city'));