简体   繁体   中英

How to use $.extend() with variables

I'm trying to make a script to use multiple values in window.location.hash but i'm having a problem with the $.extend() function of jquery

I've tried two ways, but both didn't work out.

var MultiHash = {
    params: {},

    getHash: function () {
        var hashString = document.location.hash.replace('#', '').split('&');

        for (var i=0; i < hashString.length; i++) {
            var key = hashString[i].split('=')[0];
            var value = decodeURIComponent(hashString[i].split('=')[1]);

            // First way
            var a = {key: value};

            // Second way
            var a = {};
            a[key] = value;

            $.extend(params, a);
        }

        return params;
    },

    ...
}

Is anyone seeing the problem?

first you should write :

 $.extend(this.params, a); or you cant access param

there may be other issues.

EDIT

it makes sense you return a instead of this.params in my opinion.

$.extend(a,this.params);

return a 

There are two problems wrong with what you're trying to do. The first of which being a reference problem as the params variable for that object should be referenced as this.params . The second problem being that you are not saving the result of the object extension. All of this occurs in the following line:

$.extend(params, a);

It should read something like this instead:

this.params = $.extend(this.params, a);

try this one :

var MultiHash = {
    params: {},

    getHash: function () {
        var hashString = document.location.hash.replace('#', '').split('&');

        var a = [];
        for (var i=0; i < hashString.length; i++) {
            var key = hashString[i].split('=')[0];
            var value = decodeURIComponent(hashString[i].split('=')[1]);
            a.push(key + ":'" + value + "'");           
        }

        $.extend(this.params,(new Function("return {" + a.Join(",") + "}"))());

        return this.params;
    },

    ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM