Check whether a URL variable is set using JQuery

前端 未结 2 1346
盖世英雄少女心
盖世英雄少女心 2021-02-08 23:38

I would like to know whether there is a jQuery function which can check whether a variable in the URL is set.

Something similar to the isset() function in PHP

Th

相关标签:
2条回答
  • 2021-02-09 00:04

    jQuery doesn't have native functions to get URL parameters.

    But you can write your own plugin to it:

    $.extend({
      getUrlVars: function(){
        var vars = [], hash;
        var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
        for(var i = 0; i < hashes.length; i++)
        {
          hash = hashes[i].split('=');
          vars.push(hash[0]);
          vars[hash[0]] = hash[1];
        }
        return vars;
      },
      getUrlVar: function(name){
        return $.getUrlVars()[name];
      }
    });
    

    Then you can do anything like it:

    if ($.getUrlVar("MyParam") != null) {
        // Do anything...
    }
    
    0 讨论(0)
  • 2021-02-09 00:10

    jQuery does not provide such methods. But you don’t even need jQuery to do so:

    (function() {
        var params = null;
        this.l = typeof Location !== "undefined" ? Location.prototype : window.location;
        this.l.getParameter = function(name) {
            return Array.prototype.slice.apply(this.getParameterValues(name))[0];
        };
        this.l.getParameterMap = function() {
            if (params === null) {
                params = {};
                this.search.substr(1).split("&").map(function(param) {
                    if (param.length === 0) return;
                    var parts = param.split("=", 2).map(decodeURIComponent);
                    if (!params.hasOwnProperty(parts[0])) params[parts[0]] = [];
                    params[parts[0]].push(parts.length == 2 ? parts[1] : null);
                });
            }
            return params;
        };
        this.l.getParameterNames = function() {
            var map = this.getParameterMap(), names = [];
            for (var name in map) {
                if (map.hasOwnProperty(name)) names.push(name);
            }
            return names;
        };
        this.l.getParameterValues = function(name) {
            return this.getParameterMap()[name];
        };
    })();
    

    This extends the location object with the methods getParameter, getParameterMap, getParameterNames, and getParameterValues (similar to Java’s ServeletRequest) that can be used as follows:

    if (typeof location.getParameter("foo") !== "undefined") {
        // foo parameter exists
    }
    

    The return values of getParameter have the following meaning:

    • undefined: given parameter not present
    • null: given parameter has no assigned value (e.g. foo in a=b&foo&c=d)
    • any string value otherwise.
    0 讨论(0)
提交回复
热议问题