【发布时间】:2017-08-14 23:26:47
【问题描述】:
我正在尝试制作表单的通用版本,其中下拉菜单将根据先前的下拉列表值出现,但某些下拉列表取决于两个或更多先前的答案。
我遇到的问题是得到的问题依赖于具有相同答案的同一个问题,所以当我迭代 JSON 时,它会同时显示它们,同时假设第二个问题仅在所有相关答案都得到满足时才会出现,所以我需要一种方法将它们分开。目前,ID 为 8 和 9 的问题具有相同的依赖答案,但问题 9 具有更多依赖关系。
JSON 看起来像这样:
var questions = [
//questions before these
{
Id: 6,
ProductGroups: [{
ProductGroupId: 1,
show: false
},
{
ProductGroupId: 2,
show: true
}
],
//dependant answer(s)
DependantAnswers: [{
QuestionId: 1,
answer: ""
}]
},
{
Id: 7, //guid
ProductGroups: [{
ProductGroupId: 1,
show: false
},
{
ProductGroupId: 2,
show: false
}
],
//dependant answer(s)
DependantAnswers: [{
QuestionId: 6,
answer: "male"
}]
},
{
Id: 8, //guid
ProductGroups: [{
ProductGroupId: 1,
show: false
},
{
ProductGroupId: 2,
show: false
}
],
//dependant answer(s)
DependantAnswers: [{
QuestionId: 6,
answer: "female"
}
]
},
{
Id: 9, //guid
ProductGroups: [{
ProductGroupId: 1,
show: false
},
{
ProductGroupId: 2,
show: false
}
],
//dependant answer(s)
DependantAnswers: [{
QuestionId: 6,
answer: "female"
},
{
QuestionId: 8,
answer: "yes"
}
]
}
];
这是 jQuery 函数:
function onQuestionSelectChange() {
$("#questionsContainer div select").change(function () {
var selectedValue = $(this).val();
var selectedQuestion = $(this).parent().attr('id').split('-');
var selectedQuestionId = selectedQuestion[1];
var potentialQuestions = [];
//var filteredQuestions = [];
$.each(questions, function(index, element) {
$.each(element.DependantAnswers, function (indexDepAnswer, elemDepAnswer){
if(elemDepAnswer.answer == selectedValue)
potentialQuestions.push(element);
});
});
//here I need to separate question 8 from 9 and show only question 8
});
}
通过上面的代码,我得到了一个由 2 个对象组成的数组,其中填充了问题 8 和 9,但问题 9 仅在问题 8 的回答值为“是”时才需要出现。无论我尝试什么“如果”,第 9 题都会像第 8 题一样通过,因为它具有相同的相关答案。如何过滤问题 9 并仅在我对问题 8 选择“是”后才显示它?
【问题讨论】:
标签: javascript jquery json dependencies