2013-10-11 47 views
1

我有一個非常基本的基礎和子頁面樣式實現。 我的目標是顯示用JavaScript編寫的警報,當我點擊child.html中的按鈕時。問題是,當我嘗試在子頁面中使用extra_js時,JavaScript代碼在子頁面中不起作用。但是,當它移動到base.html時,將運行相同的js塊。我錯過了什麼,爲什麼extra_ javascript代碼不能在子頁面中工作?Django額外的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 %} 

回答

4

需要在base.html以限定一個空{% block extra_js %},然後Django是放置的塊extra_js的內容child.html並將其放在父項的塊中。

base.html應該是這個樣子:

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

{% block extra_js %}{% endblock extra_js %} 
</body> 
</html> 
+0

謝謝,它的工作原理! –

相關問題