开发者

How do I use a JS variable within JSON?

I'm attempting to create a postcode lookup JQuery script that'll be able to be used multiple times on a page, without having to duplicate the script for every address on the page. The Find button has the class "postcodeLookup" and the attribute "address" which is how I intended to get the script to populate the right address (it uses JQuery Populate plugin) & the inputs are named address[line1], where "address" is changeable (home[line1], office[line1], etc.).

The problem is how to get the JSON that populates the address to use the variable contents rather than the literal word "address"?

//postcode lookups
$(".postcodeLookup").click(function(){
    alert("I am The Postcode Finder...\nPretending to find the address...\nFound it!");
    var address = $(this).attr('address');
    $("form"开发者_开发百科).populate({
        address: {
            line1: "First Line of Addr.",
            line2: "Line 2!",
            line3: "Line 3 of The Address",
            postcode: "PO1 1PO"
        }
    });
    $(".addressArea").slideDown('fast');
});


var addrName = "office";
var address = {};

address[ addrName ] = {
   line1: "First line",
   line2: "Line 2..."
};

$("form").populate( address );

Now, when addrName is office, that will be the same as writing

address['office'] = { }

... which, in turn, is exactly the same thing as writing

address.office = { }

And that little piece of knowledge will be immensely useful in all aspects of javascript.

For instance

for(var i = 0; i < 10; i++) {
    window['var' + i] = i;
}

Will actually create 10 variables in the window object (i.e. public variables) called var0, var1, ..., var9.

Ok, so that wasn't immensely useful, but you get the idea.


Probably you need to do something like this, usually jQuery plugins work this way:

line1: function(data) {return youVariable},
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜