如何在JSON中使用JS变量? [英] How do I use a JS variable within JSON?
问题描述
我正在尝试创建一个邮政编码查询JQuery脚本,该脚本将能够在页面上多次使用,而不必为页面上的每个地址重复该脚本. 查找"按钮具有类"postcodeLookup"和属性地址",这就是我打算如何使脚本填充正确的地址(它使用JQuery Populate插件)的方式.输入的名称为address [line1],其中"address"是可更改的(家庭[line1],office [line1]等).
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.).
问题是如何获取填充地址的JSON以使用变量内容而不是原义字词"address"?
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 );
现在,当addrName
为office
时,这与书写相同
Now, when addrName
is office
, that will be the same as writing
address['office'] = { }
...与写作完全相同
address.office = { }
那一点点知识对javascript的各个方面都是非常有用的.
And that little piece of knowledge will be immensely useful in all aspects of javascript.
例如
for(var i = 0; i < 10; i++) {
window['var' + i] = i;
}
实际上会在窗口对象中创建10个变量,即var0
,var1
,...,var9
.
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.
这篇关于如何在JSON中使用JS变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!