IF声明多线响应

时间:2018-04-20 21:07:51

标签: javascript html

我有以下代码,由朋友为我们一直在研究的测验系统编程。根据学生的分数显示消息

我现在需要更改代码,以便将来自IF的消息格式化为多行。有人能够指出我正确的方向。根本没有JavaScript经验。

   if(studentScore <= 150)
  var phrase = "Well done, you have achieved level bronze";
else if(studentScore <= 300)
  var phrase = "Well done, you have achieved level silver";
else if(studentScore <= 450)
  var phrase = "Well done, you have achieved level gold";
else if(studentScore <= 600)
  var phrase = "Well done, you have achieved level platinum";
else if(studentScore <= 800)
  var phrase = "Well done, you have achieved level double platinum";
else
  var phrase = "Well done, you have achieved level triple platinum";

  config = {
     elName: 'h2',
     text: phrase
  };

测验是在Articulate中创建的,我一直在处理report.html文件中的输出报告。该文件的全部内容如下:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8">
    <!-- saved from url=(0014)about:internet -->
    <title>Results</title>
    <style>

    body {
      font-family: arial;
      text-align: center;
      font-size:10pt;
    }

    table {
      border: 1px outset grey;
    }

    td, th {
      border: 1px inset grey;
    }

    table.summary {
      width: 600px;
    }

    table.questions  {
      width: 100%;
    }

    td {
      width: 12.5%;
    }

    th, h3 {
      font-size:12pt;
    }

    h1, h2 {
      font-size:14pt;
    }

    .correct {
      color: #008800;
    }

    .incorrect {
      color: #880000;
    }

    .neutral {
      color: #000088;
    }

    .question {
      text-align: left;
      width: 46.25%;
    }

    .number {
      font-size:10pt;
      width: 3.75%;
    }

    .datetime {
      font-size:10pt;
      margin-top: 0;
      margin-bottom: 0;
    }

  </style>
    <script>

var strings = {}
try {
  strings = {
    months: [
      __MONTH_JAN__,
      __MONTH_FEB__,
      __MONTH_MAR__,
      __MONTH_APR__,
      __MONTH_MAY__,
      __MONTH_JUN__,
      __MONTH_JUL__,
      __MONTH_AUG__,
      __MONTH_SEP__,
      __MONTH_OCT__,
      __MONTH_NOV__,
      __MONTH_DEC__
    ],
    dateTime: __DATE_TIME__,
    studentScore: __STUDENT_SCORE__,
    passScore: __PASSING_SCORE__,
    courseResult: __COURSE_RESULT__,
    question: __QUESTION__,
    correctAnswer: __CORRECT_ANS__,
    quizResult: __QUIZ_RESULT__,
    studentAnswer: __STUDENT_ANS__,
    pointsAwarded: __POINTS_AWARD__,
    neutral: __NEUTRAL__,
    correct: __CORRECT__,
    incorrect: __INCORRECT__
  };
} catch (e) {
  strings = {
    months: [
      'January',
      'February',
      'March',
      'April',
      'May',
      'June',
      'July',
      'August',
      'September',
      'October',
      'November',
      'December'
    ],
    dateTime: 'Date / Time',
    studentScore: 'Student Score',
    passingScore: 'Passing Score',
    courseResult: 'Result',

    question: 'Question',
    correctAnswer: 'Correct Answer',
    quizResult: 'Result',
    studentAnswer: 'Student Answer',
    pointsAwarded: 'Points Awarded',
    neutral: 'Neutral',
    correct: 'Correct',
    incorrect: 'Incorrect'
  };
}

function setupPrint(data) {
  var courseResults = data.g_oContentResults,
      quizzes = data.g_listQuizzes,
      printOptions = data.g_oPrintOptions,
      quizOrder = printOptions.arrQuizzes,
      mainQuiz = quizzes[printOptions.strMainQuizId];

  // turn date back into date object
  courseResults.dtmFinished = new Date(JSON.parse(courseResults.dtmFinished));

  function displayHeader() {
    var header = document.getElementById('header'),
        userName = printOptions.strName
        config = {
          elName: 'div',
          children: [
            { elName: 'h1', text: mainQuiz.strQuizName},
            { elName: 'h2', text: userName, enabled: userName != null && userName.length > 0},
          ]
        };

    header.appendChild(createElFromDef(config));
  }

  function displayCourseSummary() {
    var survey = printOptions.bSurvey,
        showUserScore = !survey && printOptions.bShowUserScore,
        showPassingScore = !survey && printOptions.bShowPassingScore,
        showPassFail = !survey && printOptions.bShowShowPassFail,
        studentScore = (Number(mainQuiz.nPtScore) * 14),
        passingScore = Number(mainQuiz.nPassingScore),
        courseResult = (studentScore >= passingScore) ? 'Pass' : 'Fail',
        currentDateTime = formatDate(courseResults.dtmFinished),
        courseSummary = document.getElementById('courseSummary'),
        config = {
          elName: 'table',
          attrs: [{ name: 'class', value: 'summary' }, { name: 'align', value: 'center' }],
          children: [
            { elName: 'tr',
              children: [
                { elName: 'th', text: strings.dateTime},
                { elName: 'th', text: strings.studentScore, enabled: showUserScore},
                { elName: 'th', text: strings.passingScore, enabled: showPassingScore},
                { elName: 'th', text: strings.courseResult, enabled: showPassFail}
            ]},
            { elName: 'tr',
              children: [
                { elName: 'td',
                  children: [
                    { elName: 'p', attrs: [{ name: 'class', value:'datetime' }], text: currentDateTime.date },
                    { elName: 'p', attrs: [{ name: 'class', value:'datetime' }], text: currentDateTime.time }
                ]},
                { elName: 'td', text: studentScore, enabled: showUserScore },
                { elName: 'td', text: passingScore, enabled: showPassingScore },
                { elName: 'td', text: courseResult, enabled: showPassFail }
            ]}
          ]
        };

    courseSummary.appendChild(createElFromDef(config));

    if(studentScore <= 150)
      var phrase = "Well done, you have achieved level bronze";
    else if(studentScore <= 300)
      var phrase = "Well done, you have achieved level silver";
    else if(studentScore <= 450)
      var phrase = "Well done, you have achieved level gold";
    else if(studentScore <= 600)
      var phrase = "Well done, you have achieved level platinum";
    else if(studentScore <= 800)
      var phrase = "Well done, you have achieved level double platinum";
    else
      var phrase = "Well done, you have achieved level triple platinum";

      config = {
         elName: 'h2',
         text: phrase
      };

    courseSummary.appendChild(createElFromDef(config));
  }

  function displayQuizResults() {
    for (var i = 0; i < quizOrder.length; i++) {
      var quizId = quizOrder[i];
      displayQuizResult(quizId);
    }
  };

  function displayQuizResult(quizId) {
    var i, resultsTable;
        quiz = quizzes[quizId],
        questionOrder = getQuestionOrder(quiz),
        quizDiv = createQuizDiv(quiz),
        quizReview = document.getElementById('quizReview');


    quizReview.appendChild(quizDiv);
    resultsTable = document.getElementById([ 'results-', quizId ].join(''));

    for (i = 0; i < questionOrder.length; i++) {
      var config = getQuestionConfig(quiz, questionOrder[i]);
      resultsTable.appendChild(createElFromDef(config));
    }
  };

  function createQuizDiv(quiz) {
    var survey = printOptions.bSurvey;

    return createElFromDef({
      elName: 'div',
      children: [
        { elName: 'h3', text: quiz.strQuizName },
        { elName: 'table',
          attrs: [
            { name: 'class', value: 'questions' },
            { name: 'id', value: [ 'results-', quiz.strQuizId ].join('') }
          ],
          children: [
            { elName: 'tr', children: [
              { elName: 'th', text: '#' },
              { elName: 'th', text: strings.question },
              { elName: 'th', text: strings.correctAnswer, enabled: !survey},
              { elName: 'th', text: strings.studentAnswer },
              { elName: 'th', text: strings.quizResult, enabled: !survey },
              { elName: 'th', text: strings.pointsAwarded, enabled: !survey }
          ]}
        ]}
      ]
    });
  };

  function createElFromDef(elDef) {
    if (elDef.enabled === false) {
      return null;
    }

    var el = createAndInitElement(elDef.elName, elDef.attrs, elDef.text);

    if (elDef.children != null) {
      for (var i = 0; i < elDef.children.length; i++) {
        currEl = createElFromDef(elDef.children[i]);
        if (currEl != null) {
          el.appendChild(currEl);
        }
      }
    }

    return el;
  };

  function createAndInitElement(elementName, attrs, text) {
    var el = document.createElement(elementName);

    if (attrs != null) {
      for (var i = 0; i < attrs.length; i++) {
        var attr = attrs[i];
        el.setAttribute(attr.name, attr.value);
      }
    }

    if (text != null) {
      el.appendChild(document.createTextNode(text));
    }

    return el;
  };

  function getQuestionOrder(quiz) {
    var i, j,
        questionOrder = [],
        questions = quiz.arrQuestions;

    if (questions != null && questions.length > 0)  {
      // reset
      if (questions[0].found) {
        for (var i = 0; i < questions.length; i++) {
          questions[i].found = false;
        }
      }

      for (i = questions.length - 1; i >= 0; i--) {
        var index = -1,
            maxQuestionNum = -1,
            currQuestionNum;

        for (j = 0; j < questions.length; j++) {
          currQuestionNum = Number(questions[j].nQuestionNumber);
          if (!questions[j].found && currQuestionNum > maxQuestionNum) {
            maxQuestionNum = currQuestionNum;
            if (index >= 0) {
              questions[index].found = false;
            }
            questions[j].found = true;
            index = j;
          }
        }
        questionOrder[i] = index;
      }
    }

    return questionOrder;
  }

  function getQuestionConfig(quiz, questionIdx) {
    var questions = quiz.arrQuestions,
        question = questions[questionIdx],
        survey = printOptions.bSurvey;

    return {
      elName: 'tr',
      children: [
        { elName: 'td', attrs: [{ name: 'class', value: 'number'}], text: question.nQuestionNumber },
        { elName: 'td', attrs: [{ name: 'class', value: 'question'}], text: question.strDescription },
        { elName: 'td', text: formatResponse(question.strCorrectResponse), enabled: !survey},
        { elName: 'td', text: formatResponse(question.strUserResponse) },
        { elName: 'td', attrs: [{ name: 'class', value: question.strStatus}], text: strings[question.strStatus], enabled: !survey },
        { elName: 'td', text: question.nPoints, enabled: !survey }
      ]
    };
  };

  function formatResponse(response) {
    return (response != null) ? response.replace(/\|#\|/g, ', ') : '&nbsp';
  }

  function formatDate(dtm) {
    var hours = dtm.getHours(),
        period = hours >= 12 ? 'pm' : 'am',
        minutes = dtm.getMinutes().toString(),
        month = strings.months[dtm.getMonth()],
        date = dtm.getDate(),
        year = dtm.getFullYear();

    while (minutes.length < 2) {
      minutes = '0' + minutes;
    }

    if (hours > 12) {
      hours -= 12;
    }

    return {
      date: [ month, ' ', date, ', ', year ].join(''),
      time: [ hours, ':', minutes, ' ', period ].join('')
    }
  };

  function init() {
    displayHeader();
    displayCourseSummary();
    if (printOptions.bShowQuizReview) {
      displayQuizResults();
    }
  }
  init();
}

// use post message to allow this to work locally and in 360 review
window.opener.postMessage('getQuizData', '*');

window.addEventListener('message', function (e) {
  setupPrint(JSON.parse(e.data));
}, false);

</script> </head>
  <body>
    <h1><i>Writing Certificate </i></h1>
    <div id="header"></div>
    <div id="courseSummary"></div>
    <p>&nbsp;</p>
    <div id="quizReview"></div>
  </body>
</html>

更新: 根据反馈,我将我的代码修改为以下内容(删除不需要的Var并包含在\ n)

     courseSummary.appendChild(createElFromDef(config));
    var phrase;
    if(studentScore <= 150)
     phrase = ('line one\nline two');
    else if(studentScore <= 300)
     phrase = ('line one\nline two');
    else if(studentScore <= 450)
     phrase = ('line one\nline two');
    else if(studentScore <= 600)
     phrase = ('line one\nline two');
    else if(studentScore <= 800)
     phrase = ('line one\nline two');
    else
     phrase = ('line one\nline two');

      config = {
         elName: 'h2',
         text: phrase
      };

    courseSummary.appendChild(createElFromDef(config));
  }

这已经改变了变量并引入了/ n来打破行,但是我的输出仍然在一行上。

e.g。

第一行第二行

enter image description here

是否有人能够提供更多指导 - 非常感谢

更新

刚试过&lt; br&gt;解决方案没有成功

输出只显示第一行&lt; br&gt;第二行(代码中没有空格)

enter image description here

代码如下

    courseSummary.appendChild(createElFromDef(config));
    var phrase;
    if(studentScore <= 150)
     phrase = 'line one<br>line two';
    else if(studentScore <= 300)
     phrase = 'line one<br>line two';
    else if(studentScore <= 450)
     phrase = 'line one<br>line two';
    else if(studentScore <= 600)
     phrase = 'line one<br>line two';
    else if(studentScore <= 800)
     phrase = 'line one<br>line two';
    else
     phrase = 'line one<br>line two';

      config = {
         elName: 'h2',
         text: phrase
      };

    courseSummary.appendChild(createElFromDef(config));
  }

有没有人有任何进一步的想法?

4 个答案:

答案 0 :(得分:0)

使用\n作为文字换行符:

console.log('one\ntwo');

另一种选择是使用模板文字并使用普通换行符,不需要转义字符:

console.log(`one
two`);

或者为数组中的每个项目发送一个数组,只需console.log

const phrase = ["Well done, you have achieved level:", "triple platinum"];
phrase.forEach(line => console.log(line));

另请注意,var被提升到其功能块的顶部。因此,不要对函数内的特定变量名多次使用var:只声明一次。例如

var phrase;
if(studentScore <= 150)
  phrase = "Well done, you have achieved level bronze";
else if(studentScore <= 300)
  phrase = "Well done, you have achieved level silver";

或者,更好的是,保持代码干净:

function getPhrase(studentScore) {
  const levels = [
    [0, 'bronze'],
    [150, 'silver'],
    [300, 'gold'],
    [450, 'platinum'],
    [600, 'double platinum'],
    [800, 'triple platinum'],
  ].reverse();
  const str = levels.find(([score, str]) => studentScore > score)[1];
  return ['Well done, you have achieved level:', str];
}

const appendStr = str => str.forEach(line =>
  document.body.appendChild(document.createElement('div'))
    .textContent = line
);

appendStr(getPhrase(500));
appendStr(getPhrase(200));

答案 1 :(得分:0)

使用template literal ${phrase}包装您的输出是显示多行消息的最佳方式

答案 2 :(得分:0)

使用\n或模板字符串会在JavaScript中为字符串添加换行符,但HTML会忽略它们。要在HTML中创建换行符,请使用<br>

phrase = 'hello<br>there'

答案 3 :(得分:-1)

经过一些工作后,&lt; \ BR&gt; route使用以下代码提供了最佳解决方案来控制消息

let newexportData = exportData.map(function (props) {
  let {job, ...other} = props;
  return other;
});

现在输出多行。