在HTML代码块中重用JavaScript变量

时间:2019-03-16 20:28:01

标签: javascript html

我有一段HTML,其中包含一些JavaScript,这些JavaScript利用先前捕获的userName变量来输出用户名。

目前userName作为标头过程的一部分输出:

<div id="header"></div>

在html的结尾

我想修改代码以执行其他一些操作,这需要我再花一些时间使用标头过程

目前,我只能使用一次该程序,然后将其“杀死”

有人能建议我第二次如何使用标头过程

非常感谢

<!DOCTYPE html>
<html lang="en">

<head>
  <!-- saved from url=(0014)about:internet -->
  <meta charset="utf-8">
  <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),
          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));
      }

      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>
  <div id="header"></div>
  <p>&nbsp;</p>
  <div id="courseSummary"></div>
  <p>&nbsp;</p>
  <div id="quizReview"></div>
</body>

</html>

0 个答案:

没有答案