【问题标题】:Django extra javascript is not working in the child pageDjango extra javascript 在子页面中不起作用
【发布时间】:2013-10-19 00:20:52
【问题描述】:

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

base.html

<!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>

child.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 %}

【问题讨论】:

    标签: django django-templates


    【解决方案1】:

    你需要在base.html中定义一个空的{% block extra_js %},那么Django就是将child.html的块extra_js的内容放到父块中。

    base.html 应该如下所示:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-10-06
      • 2021-01-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-19
      • 2011-07-23
      相关资源
      最近更新 更多