HTML无法在Javascript函数内部工作 - Django

时间:2012-04-18 02:43:57

标签: javascript django

我有一个包含Javascript函数的Django模板,如下所示:

<a class ="edit" href="{% url notecards.views.edit_notecard notecard.id %}"> Edit </a>
<h3 class="notecard"><p id="boldStuff">{{ notecard.notecard_name }}</p></h3>
<input id ="myButton" type="button" onclick="changeText()" value="View Answer"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.js"></script>
<script type="text/javascript">
function changeText(){
    if (document.getElementById("boldStuff").textContent == "{{ notecard.notecard_name }}")
      {
            document.getElementById("boldStuff").textContent = "{{ notecard.notecard_html|safe }}";
            $("#myButton").prop("value", "View Question");
      }
    else
      {
            document.getElementById("boldStuff").textContent = "{{ notecard.notecard_name }}";
            $("#myButton").prop("value", "View Answer");
      }
}
</script>

当变量值不是HTML时,此脚本可以正常工作。但是,当它们是HTML值时,该功能根本不起作用。单击按钮时,没有任何反应。在控制台中,我得到:

在Javascript函数的第4行上的

undetermined string literal,我在第1个函数声明行中没有定义changeText

对于有问题的其中一个值,该函数的页面源代码如下:

function changeText(){
    if (document.getElementById("boldStuff").textContent == "Here is a question hey whats up?")
      {
            document.getElementById("boldStuff").textContent = "<p>Here is an answer hey whats up. </p>
<p>Here is an answer hey whats up. Here is an answer hey whats up. </p>
<p>Here is an answer hey whats up.</p>
<p>Here is an answer hey whats up.Here is an answer hey whats up.vHere is an answer hey whats up. v</p>";
            $("#myButton").prop("value", "View Question");
      }
    else
      {
            document.getElementById("boldStuff").textContent = "Here is a question hey whats up?";
            $("#myButton").prop("value", "View Answer");
      }
}

值如图所示可以包含

标签,以及列表项等。

我尝试过同时使用.textContent.innerHTML,但问题是一样的。

谢谢

1 个答案:

答案 0 :(得分:2)

使用escapejs模板过滤器