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

我的URL只会有一个字符串

http://example.com?sent=yes

我只想检测:

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


当前回答

也许你应该给JS牙医看看?(免责声明:代码是我写的)

代码:

document.URL == "http://helloworld.com/quotes?id=1337&author=kelvin&message=hello"
var currentURL = document.URL;
var params = currentURL.extract();
console.log(params.id); // 1337
console.log(params.author) // "kelvin"
console.log(params.message) // "hello"

使用牙医JS,你基本上可以在所有字符串上调用extract()函数(例如,document.URL.extract()),你会得到所有找到的参数的HashMap。它还可以自定义处理分隔符等。

缩小版< 1kb

其他回答

2023年起的解决方案

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

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

sent存在吗?

searchParams.has('sent') // true

它等于"是"吗?

let param = searchParams.get('sent')

然后比较一下。

也许你应该给JS牙医看看?(免责声明:代码是我写的)

代码:

document.URL == "http://helloworld.com/quotes?id=1337&author=kelvin&message=hello"
var currentURL = document.URL;
var params = currentURL.extract();
console.log(params.id); // 1337
console.log(params.author) // "kelvin"
console.log(params.message) // "hello"

使用牙医JS,你基本上可以在所有字符串上调用extract()函数(例如,document.URL.extract()),你会得到所有找到的参数的HashMap。它还可以自定义处理分隔符等。

缩小版< 1kb

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

    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') { .....

jQuery代码片段,以获取动态变量存储在url作为参数,并将它们存储为JavaScript变量,以供您的脚本使用:

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

example.com ? param1 = name&param2 = id = 6

$.urlParam('param1'); // name
$.urlParam('id');        // 6
$.urlParam('param2');   // null

带有空格的参数示例

http://www.jquery4u.com?city=Gold Coast
console.log($.urlParam('city'));  
//output: Gold%20Coast



console.log(decodeURIComponent($.urlParam('city'))); 
//output: Gold Coast

最好的解决方案。

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');