【问题标题】:How to make and use a template in HTML without a framework如何在没有框架的情况下在 HTML 中制作和使用模板
【发布时间】:2018-08-19 01:05:22
【问题描述】:

如果我要进行测验,其中所有问题都需要具有相同的格式,并且一次只能向用户显示 1 个问题,我将如何在不复制和粘贴代码的情况下做到这一点?我可以做一个模板吗?那将是我的首选。


先感谢您。

【问题讨论】:

    标签: javascript jquery html templates templating


    【解决方案1】:

    如果您只想一次显示一个问题,您可以使用 JavaScript 获取问题的文本元素和选项,然后通过以下问题更改它们。

    您还可以通过 JavaScript 或其他 HTML 文件生成模板,在需要时使用 document.write()innerHTML 复制该模板。

    如何做到这一点的小例子:

    var questions = ["2 + 2", "1 + 3", "8 / 2", "5 - 2"];
    var currentQuestion = 0;
    var answers = [];
    
    function nextQuestion() {
      //Store answers:
      var value = $("input[name=options]:checked").val();
      answers.push(value);
      console.log(answers);
    
    
      //Next question:
      currentQuestion++;
      document.getElementById("question").innerHTML = questions[currentQuestion];
    
    }
    /* Apply your styles*/
    
    #question {
      color: red;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div id="question">2 + 2?</div>
    <form action="">
      <input type="radio" name="options" value="5">5<br>
      <input type="radio" name="options" value="4">4<br>
      <input type="radio" name="options" value="3">3
    </form>
    
    <button onclick="nextQuestion()">next question</button>

    https://jsfiddle.net/z0n4xekh/23/

    【讨论】:

    • 我该怎么做?
    • 1 秒。我写一个例子。
    • 您可以进一步阐述它并根据您的需要进行调整。
    • answers.push 有什么作用?它只是为数组增加价值吗?
    • 向数组添加一个新元素,在这种情况下是附加选定的值。在控制台中,您可以看到数组如何存储选定的选项。
    猜你喜欢
    • 2016-12-04
    • 1970-01-01
    • 2018-05-29
    • 2017-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-27
    • 2014-05-07
    相关资源
    最近更新 更多