Branching logic quiz — where am I going wrong? [JavaScript]

≯℡__Kan透↙ 提交于 2021-02-08 08:27:22

问题


I am trying to develop logic for a "simple" jQuery quiz [Fiddle here]. The problem is, the question path is somewhat dynamic, and produces a tree structure.

For example, the first question is about pets: dog, cat, or bird? If you choose dog, it asks what breed dog. If you choose cats, it asks what breed cat. Etc. Then it delves deeper ("What color dog of this particular breed?")

The problem I am having is getting to that third set of questions. I can't get the color question to work for any of the dogs. In fact, the click handler doesn't even fire. Can anyone tell me where I've fouled this up?

Thank you in advance.

var questions = [{
    "text": "What's your favorite pet?",
    "choices": [
        {
            "label": "Dog",
            "path": 1
        },
        {
            "label": "Cat",
            "path": 2
        },
        {
            "label": "Bird",
            "path": 3
        },
    ]
}, {
    "text": "What breed of dog?", //1 a
    "choices": [
        {
            "label": "Golden Retriever",
            "path": 4
        },
        {
            "label": "Labrador",
            "path": 5
        },
        {
            "label": "Poodle",
            "path": 6
        },
    ]
}, {
    "text": "What breed of cat?", //1 b
    "choices": [
        {
            "label": "Siamese",
            "path": 4
        },
        {
            "label": "Persian",
            "path": 4
        },
        {
            "label": "Tortie",
            "path": 4
        },
    ]
}, {
    "text": "What breed of bird?", //1 c
    "choices": [
        {
            "label": "Bluebird",
            "path": 4
        },
        {
            "label": "Robin",
            "path": 4
        },
        {
            "label": "Parrot",
            "path": 4
        },
    ]
}, {
    "text": "What color Golden Retriever?", //1 a i
    "choices": [
        {
            "label": "Golden",
            "path": 4
        },
        {
            "label": "Sandy",
            "path": 4
        },
        {
            "label": "Blonde",
            "path": 4
        },
    ]
}, {
    "text": "What color Labrador?", //1 b i
    "choices": [
        {
            "label": "Black",
            "path": 4
        },
        {
            "label": "Chocolate",
            "path": 4
        },
        {
            "label": "Tan",
            "path": 4
        },
    ]
}, {
    "text": "What color Poodle?", //1 c i
    "choices": [
        {
            "label": "Ugly",
            "path": 4
        },
        {
            "label": "Uglier",
            "path": 4
        },
        {
            "label": "Ugliest",
            "path": 4
        },
    ]
}];

var currentQuestion = 0,
    quizComplete = false;

$(document).ready(function() {

    updateQuestion();

    if (!quizComplete) {

        $('.choice').on('click', function() {

        value = $(this).attr('value');
            currentQuestion = value;

            if (currentQuestion < questions.length) {
                updateQuestion();
            } else {
                quizComplete = true;
            }

        });

    }

});

function updateQuestion() {

    var question = questions[currentQuestion].text;
    var questionText = $(document).find(".container > .question");
    var choiceList = $(document).find(".container > .choices");
    var numChoices = questions[currentQuestion].choices.length;

    // Set question text
    $(questionText).text(question);

    // Clear current choices and update with new ones
    $(".choice").remove();

    var choice, path;
    for (i = 0; i < numChoices; i++) {
        choice = questions[currentQuestion].choices[i].label;
        path = questions[currentQuestion].choices[i].path;
        $('<div class="choice" value=' + path + '>' + choice + '</div>').appendTo(choiceList);
    }
}

回答1:


Use $(document).on('click', '.choice', function() {}); which will work even when you remove and re-add the .choice element. And change the currentQuestion to get incremented each time he/she answers so that we can track the number of questions answered.

Update:-

Your logic doesn't seem to be working perfect. So change the object structure slightly like the following demo

var questions = {
  "text": "What's your favorite pet?",
  "choices": [{
      "label": "Dog",
      "path": 1,
      "question": {
        "text": "What breed of dog?", //1 a
        "choices": [{
            "label": "Golden Retriever",
            "path": 11,
            "question": {
              "text": "What color Golden Retriever?", //1 a
              "choices": [{
                  "label": "Golden",
                  "path": 111
                },
                {
                  "label": "Sandy",
                  "path": 112
                },
                {
                  "label": "Blonde",
                  "path": 113
                },
              ]
            }
          },
          {
            "label": "Labrador",
            "path": 12,
            "question": {
              "text": "What color Labrador?", //1 a
              "choices": [{
                  "label": "Black",
                  "path": 121
                },
                {
                  "label": "Chocolate",
                  "path": 122
                },
                {
                  "label": "Tan",
                  "path": 123
                },
              ]
            }
          },
          {
            "label": "Poodle",
            "path": 13,
            "question": {
              "text": "What color Poodle?", //1 a
              "choices": [{
                  "label": "Ugly",
                  "path": 131
                },
                {
                  "label": "Uglier",
                  "path": 132
                },
                {
                  "label": "Ugliest",
                  "path": 133
                },
              ]
            }
          },
        ]
      }
    },
    {
      "label": "Cat",
      "path": 2,
      "question": {
        "text": "What breed of cat?", //1 b
        "choices": [{
            "label": "Siamese",
            "path": 21,
            "question": {
              "text": "What color Siamese?", //1 a
              "choices": [{
                  "label": "white",
                  "path": 211
                },
                {
                  "label": "orange",
                  "path": 212
                },
                {
                  "label": "red",
                  "path": 213
                },
              ]
            }
          },
          {
            "label": "Persian",
            "path": 22,
            "question": {
              "text": "What color Persian?", //1 a
              "choices": [{
                  "label": "lavendar",
                  "path": 221
                },
                {
                  "label": "green",
                  "path": 222
                },
                {
                  "label": "black",
                  "path": 223
                },
              ]
            }
          },
          {
            "label": "Tortie",
            "path": 23,
            "question": {
              "text": "What color Tortie?", //1 c
              "choices": [{
                  "label": "violet",
                  "path": 231
                },
                {
                  "label": "orange",
                  "path": 232
                },
                {
                  "label": "Pink",
                  "path": 233
                },
              ]
            }
          },
        ]
      }
    },
    {
      "label": "Bird",
      "path": 3,
      "question": {
        "text": "What breed of bird?", //1 a
        "choices": [{
            "label": "Bluebird",
            "path": 31,
            "question": {
              "text": "What breed of Bluebird?", //1 a
              "choices": [{
                  "label": "Blue",
                  "path": 311
                },
                {
                  "label": "grey",
                  "path": 312
                },
                {
                  "label": "yellow",
                  "path": 313
                },
              ]
            }
          },
          {
            "label": "Robin",
            "path": 32,
            "question": {
              "text": "What breed of Robin?", //1 a
              "choices": [{
                  "label": "Black",
                  "path": 321
                },
                {
                  "label": "White",
                  "path": 322
                },
                {
                  "label": "Red",
                  "path": 323
                },
              ]
            }
          },
          {
            "label": "Parrot",
            "path": 33,
            "question": {
              "text": "What breed of Parrot?", //1 a
              "choices": [{
                  "label": "Multi Color",
                  "path": 331
                },
                {
                  "label": "Red",
                  "path": 332
                },
                {
                  "label": "Green",
                  "path": 333
                },
              ]
            }
          },
        ]
      }
    },
  ]
};

var quizComplete = false,
  answers = [],
  currentObj = questions;

$(document).ready(function() {

  updateQuestion();

  if (!quizComplete) {

    $('.choices').on('click', '.choice', function() {

      value = $(this).attr('value');
      answers.push($(this).html());
      //currentQuestion++;

      if (currentObj.choices[value].question) {
        currentObj = currentObj.choices[value].question;
      } else {
        quizComplete = true;
        alert("quizComplete answers : " + answers);
        answers = [];
        currentObj = questions;
      }
      updateQuestion();

    });

  }
});

function updateQuestion() {

  var question = currentObj.text;
  var questionText = $(document).find(".container > .question");
  var choiceList = $(document).find(".container > .choices");
  var numChoices = currentObj.choices.length;

  // Set question text
  $(questionText).text(question);

  // Clear current choices and update with new ones
  $(".choice").remove();

  var choice, path;
  for (i = 0; i < numChoices; i++) {
    choice = currentObj.choices[i].label;
    path = currentObj.choices[i].path;
    $('<div class="choice" value=' + i + '>' + choice + '</div>').appendTo(choiceList);
  }
}
body {
  font-family: serif;
}

h1 {
  text-align: center;
}

.container {
  background-color: peachpuff;
  border-radius: 6px;
  width: 75%;
  margin: auto;
  padding-top: 5px;
  box-shadow: 10px 10px 5px #888;
  position: relative;
}

.question {
  font-size: 2em;
  width: 90%;
  height: auto;
  margin: auto;
  border-radius: 6px;
  background-color: goldenrod;
  text-align: center;
}

.choices {
  font-family: Courier, serif;
  color: indianred;
  margin-top: 2em;
}

.choice {
  cursor: pointer;
  font-size: 2em;
  text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<body>

  <div class="container">
    <div class="question"></div>
    <div class="choices"></div>
  </div>

</body>



回答2:


click Event has to be added everytime updating a Questions. Here updated code

var questions = [{
	"text": "What's your favorite pet?",
	"choices": [
		{
			"label": "Dog",
			"path": 1
		},
		{
			"label": "Cat",
			"path": 2
		},
		{
			"label": "Bird",
			"path": 3
		},
	]
}, {
	"text": "What breed of dog?", //1 a
	"choices": [
		{
			"label": "Golden Retriever",
			"path": 4
		},
		{
			"label": "Labrador",
			"path": 5
		},
		{
			"label": "Poodle",
			"path": 6
		},
	]
}, {
	"text": "What breed of cat?", //1 b
	"choices": [
		{
			"label": "Siamese",
			"path": 4
		},
		{
			"label": "Persian",
			"path": 4
		},
		{
			"label": "Tortie",
			"path": 4
		},
	]
}, {
	"text": "What breed of bird?", //1 c
	"choices": [
		{
			"label": "Bluebird",
			"path": 4
		},
		{
			"label": "Robin",
			"path": 4
		},
		{
			"label": "Parrot",
			"path": 4
		},
	]
}, {
	"text": "What color Golden Retriever?", //1 a i
	"choices": [
		{
			"label": "Golden",
			"path": 4
		},
		{
			"label": "Sandy",
			"path": 4
		},
		{
			"label": "Blonde",
			"path": 4
		},
	]
}, {
	"text": "What color Labrador?", //1 b i
	"choices": [
		{
			"label": "Black",
			"path": 4
		},
		{
			"label": "Chocolate",
			"path": 4
		},
		{
			"label": "Tan",
			"path": 4
		},
	]
}, {
	"text": "What color Poodle?", //1 c i
	"choices": [
		{
			"label": "Ugly",
			"path": 4
		},
		{
			"label": "Uglier",
			"path": 4
		},
		{
			"label": "Ugliest",
			"path": 4
		},
	]
}];

var currentQuestion = 0,
    quizComplete = false;

$(document).ready(function () {

	updateQuestion();

});
//separating next Question
function nextQuestion() {
if (!quizComplete) {

		$('.choice').on('click', function() {

  		value = $(this).attr('value');
			currentQuestion = value;
		
			if (currentQuestion < questions.length) {
				updateQuestion();
			} else {
        quizComplete = true;
      }

		});
    
	}
}

function updateQuestion() {

	var question = questions[currentQuestion].text;
	var questionText = $(document).find(".container > .question");
	var choiceList = $(document).find(".container > .choices");
	var numChoices = questions[currentQuestion].choices.length;

	// Set question text
	$(questionText).text(question);

	// Clear current choices and update with new ones
	$(".choice").remove();

	var choice, path;
	for (i = 0; i < numChoices; i++) {
		choice = questions[currentQuestion].choices[i].label;
		path = questions[currentQuestion].choices[i].path;
		$('<div class="choice" value=' + path + '>' + choice + '</div>').appendTo(choiceList);
	}
  //It needs to be called every update
  nextQuestion();
}
body {
    font-family: serif;
}
h1 {
    text-align: center;
}

.container {
    background-color: peachpuff;
    border-radius: 6px;
    width: 75%;
    margin: auto;
    padding-top: 5px;
    box-shadow: 10px 10px 5px #888;
    position: relative;
}
.question {
    font-size: 2em;
    width: 90%;
    height: auto;
    margin: auto;
    border-radius: 6px;
    background-color: goldenrod;
    text-align: center;
}
.choices {
    font-family: Courier, serif;
    color: indianred;
    margin-top: 2em;
}
.choice {
    cursor: pointer;
    font-size: 2em;
    text-align: center;
}
	<body>

	    <div class="container">
	        <div class="question"></div>
	        <div class="choices"></div>
	    </div>

	</body>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>


来源:https://stackoverflow.com/questions/46701628/branching-logic-quiz-where-am-i-going-wrong-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!