我的听众有一个简单的问题。因此,在到达我的应用程序主页时,Django 会提供以下 html:
<!DOCTYPE html>
{% load staticfiles %}
<html>
<head>
{% csrf_token %}
<title>Tempo</title>
<link rel="stylesheet" type="text/css" href="{% static "css/styles.css" %}">
<link rel="stylesheet" type="text/css" href="{% static "css/bootstrap.min.css" %}">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script>
$( "#myform" ).on( "submit", function( event ) {
console.log("This should fire after form submission")
});
$( "#myform" ).submit(function() {
console.log("This should fire after form submission")
});
</script>
</head>
<body>
<div id="header">
<img id="logo" src="{% static "img/logo_wt.svg" %}"/>
</div>
{% csrf_token %}
<form id="myform" action="/" method="POST" enctype="multipart/form-data">
{% csrf_token %}
<input type="file" name="csvFile">
<input type="submit" value="Submit">
</form>
</body>
我想在提交表单后执行一组操作,但由于某种原因我无法触发事件监听器。我已经尝试了 on
和 submit
方法,但没有成功。任何人都知道发生了什么
最佳答案
它不起作用,因为当脚本执行时,#myform 还不存在。
有两种解决方法:
一个。创建表单后,将脚本放在文档的末尾。
这是首选解决方案。将 JS 放在主体的末尾现在被认为是最佳实践,因为它允许 DOM 先加载和绘制,让用户感知到的页面加载时间稍快一些。
<!DOCTYPE html>
{% load staticfiles %}
<html>
<head>
{% csrf_token %}
<title>Tempo</title>
<link rel="stylesheet" type="text/css" href="{% static "css/styles.css" %}">
<link rel="stylesheet" type="text/css" href="{% static "css/bootstrap.min.css" %}">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
</head>
<body>
<div id="header">
<img id="logo" src="{% static "img/logo_wt.svg" %}"/>
</div>
{% csrf_token %}
<form id="myform" action="/" method="POST" enctype="multipart/form-data">
{% csrf_token %}
<input type="file" name="csvFile">
<input type="submit" value="Submit">
</form>
<script>
$( "#myform" ).on( "submit", function( event ) {
console.log("This should fire after form submission")
});
$( "#myform" ).submit(function() {
console.log("This should fire after form submission")
});
</script>
</body>
</html>
B.或者,将其封装在文档就绪的处理程序中,该处理程序将在 DOM 完全加载后执行(有关更多详细信息,请参见此处:https://api.jquery.com/ready/):
<script>
$(function() {
$( "#myform" ).on( "submit", function( event ) {
console.log("This should fire after form submission")
});
$( "#myform" ).submit(function() {
console.log("This should fire after form submission")
});
});
</script>
PS - 您使用的两种事件处理方法都可以使用。您可以消除一个以防止事件重复。
关于javascript - 表单提交的监听器不适用于 jQuery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31911175/