我的json:
function serverValidateQuestion(survey, options) {
console.log('Validation called');
console.log(options);
console.log(options.data.numhousehold);
console.log(options.data.householdtype);
console.log(options.data.householdtype.children);
我的JavaScript是:
any
这样我可以访问“ console.log(options.data.householdtype)”,它为我提供了家用类型的项目列表。但是,我试图访问来自familytype的“儿童”值输入。当我编写console.log(options.data.householdtype.children)时,它给我“无法读取未定义的属性”错误
答案 0 :(得分:0)
var options = {
"locale": "en",
"title": " Survey",
"focusFirstQuestionAutomatic": false,
"pages": [{
"name": "livingEnvironment",
"elements": [{
"type": "html",
"name": "navigationWarning",
"html": "warning"
},
{
"type": "html",
"name": "IntroEnvironment",
"html": "We will now ask you questions about your living environment ."
},
{
"type": "text",
"name": "numhousehold",
"width": "auto",
"title": "How many people (including yourself) lived in your household at the time of Hurricane Harvey? ",
"validators": [{
"type": "numeric",
"text": "Please enter a number between 1 and 99.",
"minValue": 1,
"maxValue": 99
},
{
"type": "expression",
"text": "you wrong here",
"expression": "{numhousehold} > {householdtype.children}"
}
],
"inputType": "number"
},
{
"type": "multipletext",
"name": "householdtype",
"width": "auto",
"title": "Of these, how many (including yourself) were:",
"items": [{
"name": "children",
"inputType": "number",
"title": "Children under 18 years old",
"validators": [{
"type": "regex",
"text": "One of the numbers below is out of range. Please enter 0, a positive number, or leave the box blank.",
"regex": "^(\\s*|\\d+)$"
}]
},
{
"name": "adults",
"inputType": "number",
"title": "Adults between 18-59 years old",
"validators": [{
"type": "regex",
"text": "One of the numbers below is out of range. Please enter 0, a positive number, or leave the box blank.",
"regex": "^(\\s*|\\d+)$"
}]
},
{
"name": "seniors",
"inputType": "number",
"title": "Seniors (60+)",
"validators": [{
"type": "regex",
"text": "One of the numbers below is out of range. Please enter 0, a positive number, or leave the box blank.",
"regex": "^(\\s*|\\d+)$"
}]
}
]
}
]
}]
};
//var options = JSON.parse(str); //don't need if it's already JSON
console.log('Validation called');
console.log(options.pages[0].elements[3].items[0].name); //accesses elements without a loop
//loop through all the nested elements to get the names
for(var page in options.pages) {
console.log("Page name: " + options.pages[page].name);
for(var element in options.pages[page].elements) {
console.log("Element name: " + options.pages[page].elements[element].name);
for(var item in options.pages[page].elements[element].items) {
console.log("Item name: " + options.pages[page].elements[element].items[item].name);
}
}
}
这是我根据您的新问题解答的最新答案:
同样,“子项”位于“项”数组中:“ householdtype”下没有数组。另外,如果您可以控制接收到的json,则将其保留为上面显示的json格式(而不是字符串)有助于使代码更简单,更易于调试,并且您不必使用parse()
。