我得到了:
未捕获的TypeError:无法读取未定义的属性“0”
尝试使用参数动态引用javascript对象时。虽然当我尝试传递单个参数virtual_page_no
时它正在工作,但它在传递2个参数时开始出错。
// Json list
var patients = {
"patient_1": [
{
"page_no": "3",
"quest_response_headline": "Question1",
"quest_response": "Response1",
"quest_next_link": "View Answer"
},
{
"page_no": "4",
"quest_response_headline": "Question2",
"quest_response": "Response2",
"quest_next_link": "Next Question >"
}
]
}
var current_virtual_page = 0;
var next_virtual_page = current_virtual_page + 1;
function quest_response_text(i, virtual_page_no) {
var quest_response_headline = patients.patient_i[virtual_page_no].quest_response_headline;
var quest_response = patients.patient_i[virtual_page_no].quest_response;
var quest_next_link = patients.patient_i[virtual_page_no].quest_next_link;
$('.quest-response-headline').text(quest_response_headline);
$('.quest-response').text(quest_response);
$('.quest-next-link').text(quest_next_link);
}
// init
quest_response_text(1, current_virtual_page);
// When user click on view answer or next question link
$('.quest-next-link').on('click', function () {
quest_response_text(next_virtual_page);
});
答案 0 :(得分:1)
如果您想使用patients.patient_1
变量动态访问i
,请尝试使用:
patients['patient_' + i]
所以看起来应该是这样的:
var quest_response_headline = patients['patient_' + i][virtual_page_no].quest_response_headline;