微信小程序实现答题样式3(记录得分)

首先在上一篇的基础上新增了一个正确答案以及对应的分数,具体的结构如下:

data: {
    quest: [{
      id: 1,
      type: 1, //类型,1.单选,2.多选
      question: "1.C语言是面向对象程序设计语言?",
      answers: [{
        index: 'A',
        content: '是'
      }, {
        index: 'B',
        content: '不是'
      }],
      correctAnswer: 'B',
      scope: 5,
    }, {
      id: 2,
      type: 1,
      question: "2.以下哪个不是面向对象程序设计语言的基本特征?",
      answers: [{
        index: 'A',
        content: '多态'
      }, {
        index: 'B',
        content: '继承'
      }, {
        index: 'C',
        content: '封装'
      }, {
        index: 'D',
        content: '接口'
      }],
      correctAnswer: 'D',
      scope: 5,
    }, {
      id: 3,
      type: 2,
      question: "3.以下哪种是面向对象程序设计语言?",
      answers: [{
        index: 'A',
        content: 'Java'
      }, {
        index: 'B',
        content: 'C语言'
      }, {
        index: 'C',
        content: 'C++'
      }, {
        index: 'D',
        content: 'Python'
      }, {
        index: 'E',
        content: 'C#'
      }],
      correctAnswer: 'ACDE',
      scope: 5,
    }]
  },

然后wxml也稍微修改一下,具体如下:


  {{item.question}}{{item.type==1?'(单选)':'(多选)'}}
  
    {{item.index}}.
     {{item.content}}
  

提交

wxss还是不变,点击提交按钮时根据选中的答案判断得分,具体代码如下:

 // 点击提交按钮
  submit() {
    let {
      quest
    } = this.data;
    let totalScope = 0; //记录分数
    //用来保存选中的答案
    let answerSelected = [];
    for (let questItem of quest) {
      if (questItem.type == 1) { //处理单选题
        let isSelected = false;
        for (let answerItem of questItem.answers) {
          if (answerItem.selected) {
            //答案被选中
            isSelected = true;
            answerSelected.push(answerItem.index);
          }
        }
        if (!isSelected) {
          //如果一个都没选
          answerSelected.push('');
        }
      } else { //处理多选题
        let multiAnswer = [];
        for (let answerItem of questItem.answers) {
          if (answerItem.selected) {
            //答案被选中
            multiAnswer.push(answerItem.index);
          }
        }
        answerSelected.push(multiAnswer.join(''));
      }
      totalScope += questItem.correctAnswer == answerSelected[answerSelected.length - 1] ? questItem.scope : 0;
    }
    console.log(answerSelected);
    console.log(totalScope);
  }

最终效果如下:

微信小程序实现答题样式3(记录得分)_第1张图片

 

你可能感兴趣的:(微信小程序,答题,微信小程序,答题,得分)