【问题标题】:jQuery - How to separate two objects which are dependent on same object?jQuery - 如何分离依赖于同一对象的两个对象?
【发布时间】: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


    【解决方案1】:

    这是执行此操作的一种方法,其中您有一系列已回答的问题,以便您可以跟踪哪些潜在的问题是有效的。我相信你可以优化这个,但是这个是为了展示如何以一种相当简单的方式来做。希望这会有所帮助。

    let selectedValue = 'female';
    // Push selectedValue into some array to keep track of current answers
    let selectedValues = [
      {QuestionId: 1, answer: 'q1'},
      {QuestionId: 2, answer: 'q2'},
      {QuestionId: 3, answer: 'q3'},
      {QuestionId: 4, answer: 'q4'},
      {QuestionId: 5, answer: 'q5'},
      {QuestionId: 6, answer: 'female'}
    ];
    
    let resultingQuestions = [];
    
    questions.filter((q) => {
      return q.DependantAnswers.find((dp) => { 
        return dp.answer === selectedValue;
      });
    }).filter((pq) => {
      let validQuestion;
      pq.DependantAnswers.forEach((da) => {
        validQuestion = selectedValues.find((sv) => {
          return sv.QuestionId === da.QuestionId && sv.answer === da.answer;
        }); 
      });
    
      if (validQuestion) {
        resultingQuestions.push(pq);
      }
    });
    

    【讨论】:

      【解决方案2】:

      您当前解决方案的问题是您正在检查问题数组中当前选择的答案,如果您发现当前选择的答案在任何问题的相关答案列表中,那么您正在考虑该问题作为潜在的下一个问题,即使该问题可能具有多个可能无法满足的依赖关系,但由于您没有保持任何状态,因此您无法检查它们。

      您可以做的一件事是创建一个哈希图,它只跟踪已回答的问题,并在检查下一个潜在问题查找时是否满足所有依赖关系。

      所以我假设你的原始函数在每次选择更改时都会被调用。

      var questionsCompleted = Object.create(null);
      
      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 = [];
      
              // Update the Hashmap 
              questionsCompleted[selectedQuestionId] = selectedValue;
      
              // Check all the questions for the next potential question. The next potential question will be the one whose all dependent question are already answered
              $.each(questions, function(index, element) {
                  var fulfilled = 0;
                  $.each(element.DependantAnswers, function(indexDepAnswer, elemDepAnswer) {
                      if (elemDepAnswer.answer === questionsCompleted[element.Id])
                          fulfilled++;
      
                  });
                  if (fulfilled === element.DependantAnswers.length) // All dependency fulfilled
                      potentialQuestions.push(element);
      
              });
              //here I need to separate question 8 from 9 and show only question 8
      
          });
      
      } 
      

      希望这会有所帮助。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-04-06
        • 1970-01-01
        • 2021-09-19
        • 1970-01-01
        • 2020-01-25
        相关资源
        最近更新 更多