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

我的URL只会有一个字符串

http://example.com?sent=yes

我只想检测:

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


当前回答

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

其他回答

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;
}

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

还有一个使用URI.js库的例子。

例子准确地回答了所问的问题。

var url = 'http://example.com?sent=yes'; var urlParams = new URI(url).search(true); // 1. Does sent exist? var sendExists = urlParams.sent !== undefined; // 2. Is it equal to "yes"? var sendIsEqualtToYes = urlParams.sent == 'yes'; // output results in readable form // not required for production if (sendExists) { console.log('Url has "sent" param, its value is "' + urlParams.sent + '"'); if (urlParams.sent == 'yes') { console.log('"Sent" param is equal to "yes"'); } else { console.log('"Sent" param is not equal to "yes"'); } } else { console.log('Url hasn\'t "sent" param'); } <script src="https://cdnjs.cloudflare.com/ajax/libs/URI.js/1.18.2/URI.min.js"></script>

使用这个

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