我試圖製作一個通用版本的窗體,其中顯示的下拉菜單取決於之前的下拉值,但某些下拉菜單依賴於兩個或更多以前的答案。jQuery - 如何分離依賴於同一對象的兩個對象?
我遇到的問題是,依賴於相同問題的問題具有相同的答案,所以當我迭代JSON時,它將兩者都顯示出來,同時第二個問題假設只在所有依賴答案滿足時出現,所以我需要一種方法來分開它們。目前,Id 8和Id 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
});
}
利用上述代碼我得到填充有問題8和9 2個對象的數組,但問題9個需要只有當問題8的回答值爲「是」時纔出現。無論我嘗試什麼「如果」,問題9都會像問題8一樣傳遞,因爲它具有相同的相關答案。我如何過濾問題9並僅在問題8選擇「是」之後才顯示它?