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

我的URL只会有一个字符串

http://example.com?sent=yes

我只想检测:

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


当前回答

也许太晚了。但是这种方法非常简单易行

<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery.url.js"></script>

<!-- URL:  www.example.com/correct/?message=done&year=1990 -->

<script type="text/javascript">
$(function(){
    $.url.attr('protocol')  // --> Protocol: "http"
    $.url.attr('path')      // --> host: "www.example.com"
    $.url.attr('query')         // --> path: "/correct/"
    $.url.attr('message')       // --> query: "done"
    $.url.attr('year')      // --> query: "1990"
});

更新 需要url插件:plugins.jquery.com/url 由于-Ripounet

其他回答

还有一个使用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>

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

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

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

还有另一种功能……

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