Django额外的javascript在子页面中不起作用

Co *_*der 3 django django-templates

我有一个非常基本的基本和子页面样式实现。我的目标是显示用 javascript 编写的警报,当我单击child.html. 问题是当我尝试extra_js在子页面中使用时,javascript 代码在子页面中不起作用。但是,相同的 js 块在移动到base.html. 我错过了什么,为什么extra_ javascript代码在子页面中不起作用?

基本文件

<!DOCTYPE html>
<html lang="en">
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>


{% comment %} 
When I enable these lines, it works.Why??? it does not work in the child page???
   <script>
    function myfunction2(){
        alert("The button is clicked in child page!");
    }
</script>{% endcomment %}
    <body>
    <div id="sidebar">
        {% block sidebar %}
            <ul>
                <li><a href="/">Home</a></li>
                <li><a href="/blog/">Blog</a></li>
            </ul>
        {% endblock %}
    </div>

    <div id="content">
        {% block content %}{% endblock %}
    </div>
    </body>
    </html>
Run Code Online (Sandbox Code Playgroud)

孩子.html

{% extends "base.html" %}

{% block extra_css %}
    <style type="text/css">

        #mydiv{
            height: 50px;
            width:200px;
            margin-top:5px;
            border:2px solid;
        }

    </style>
{% endblock %}

{% block extra_js %}
    <script>
    function myfunction2(){
    alert("The button is clicked in child page!");
    }
    </script>
{% endblock %}
{% block content %}

    <h2>Child page</h2>

    <div id="mydiv">
    <p>
        Some text goes here...
    </p>
    </div>

    <input type="submit"  class="field button"  style="float: left; " name="submit"  value="Submit" id="Submit1" onclick ="myfunction2();"> </input>


{% endblock %}
Run Code Online (Sandbox Code Playgroud)

小智 8

您需要定义一个空{% block extra_js %}base.html,那么Django是把块的内容extra_jschild.html,并将其放置在父块。

base.html 应该是这样的:

<html>
<head></head>
<body>
...
<div id="content">
{% block content %}{% endblock content %}
</div>

{% block extra_js %}{% endblock extra_js %}
</body>
</html>
Run Code Online (Sandbox Code Playgroud)