$.html() returns undefined?

$.html() returns undefined?

本文关键字:undefined returns html      更新时间:2023-09-26

这行代码($('#quiz-template').html();)总是返回undefined,尽管存在一个ID为'quiz-template'的脚本元素。我不知道是什么问题。你们有过这样的经历吗?如有任何帮助,不胜感激。

index . html:

<script id="quiz-template" type="text/html">
  <h1>{{question}}</h1>
  <hr>
  <p class="right" style="display: none;">Richtig!</p>
  <p class="wrong" style="display: none;">{{explanation}}</p>
  <form id="answerswerForm" action="javascript:submitValue();">
    {{#possibleAnswers}}
    <div><label><input type="radio" name="answerswer" value="{{.}}">{{.}}</label></div>
    {{/possibleAnswers}}
    <input type="submit" value="Antwort bestätigen">
  </form>
</script>

app.js:

showPage = function(pageIndex) {
    currentPageIndex = pageIndex;
    if (currentPageIndex == 0) {
        template = $('#start-template').html();
        console.log($('#start-template').html())
        $('#content').html(Mustache.render(template));
    }
    else if (currentPageIndex == 11) {
        template = $('#end-template').html();
        $('#content').html(Mustache.render(template), tally);
    }
    else {
        template = $('#quiz-template').html(); // this returns undefined
        console.log($('#quiz-template').html());
        question = pickRandomQuestion();
        $('#content').html(Mustache.render(template, question));
    }
};

确保在文档加载时执行showPage函数。你查过了吗?

编辑:我认为你不能得到html的原因是因为"脚本"标签。我建议使用以下两种:

1) Simple:
<textarea id="name" style="display:none">
        ... templates ...
</textarea>

2) Valid XHTML 1.1 (using CDATA):
<p style="display:none"><textarea id="name" rows="0" cols="0"><![CDATA[
        ... templates ...
]]></textarea></p>

3) Valid XHTML 1.1 (using comments; suggested):
<p style="display:none"><textarea id="name" rows="0" cols="0"><!--
        ... templates ...
--></textarea></p>