我有以下 django 模板,我在其中定义了一个按钮,以便它调用我添加到页面的 javascript 函数,如下所示。我有以下问题:
1) 如果我将脚本标签带到 header 部分,则不会显示任何内容。
2) 如果按下按钮,我会收到未定义的错误消息。 (未捕获的 ReferenceError:postData)。
我在说什么?
非常感谢, 迈克
newproduct.html
{% load staticfiles %}
<!DOCTYPE html>
<html>
<head>
<title>New Product</title>
</head>
<body>
<p>Hellow</p>
<a href="/">Back</a>
<h2>Please enter product details:</h2>
<button onclick="postData();">Send Post</button>
<form action="http://127.0.0.1:8000/newproduct/" method="post">
<p>{{ message }}</p>
{% csrf_token %}
{{ form.as_p }}
<input type="submit"/>
</form>
<script src="bower_components/jquery/src/jquery.js" type="text/javascript"/>
<script src="scripts/main.js" />
</body>
</html>
main.js
function postData ()
{
$.post('/newproduct', {name:'New Product JS', price:555, });
};
最佳答案
您已经在 HTML 中硬编码了对 postData
的引用,但是您在定义它之前已经使用了它,因为 JS 直到页面末尾才加载.
你可以通过将脚本移动到 HTML 的顶部来解决这个问题,但最好不要像这样直接在 HTML 中使用 JS。相反,您的脚本本身应该使用 jQuery dom-ready 功能将自身绑定(bind)到按钮事件。
html:
<h2>Please enter product details:</h2>
<button id="my_button">Send Post</button>
主要.js
$(function() {
$('#my_button').click(function() {
$.post('/newproduct', {name:'New Product JS', price:555, });
});
});
关于javascript - django 模板无法调用 javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40720761/