Check whether a URL variable is set using JQuery

前端 未结 2 1395
盖世英雄少女心
盖世英雄少女心 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: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.

提交回复
热议问题