Jquery .on() 提交事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18545941/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Jquery .on() submit event
提问by Anton Abramov
I've got a problem with .on()
.
I have multiple form-elements (forms with class="remember"
), also I add another one form.remember
using AJAX.
So, I want it to handle submit event something like:
我有问题.on()
。我有多个表单元素(带有 的表单class="remember"
),我还form.remember
使用 AJAX添加了另一个。所以,我希望它处理提交事件,例如:
$('form.remember').on('submit',function(){...})
but form added with AJAX doesn't work with it.
但是用 AJAX 添加的表单不起作用。
Where is the problem? Is it a bug?
问题出在哪儿?这是一个错误吗?
回答by Dipesh Parmar
You need to delegate event to the document level
您需要将事件委托给文档级别
$(document).on('submit','form.remember',function(){
// code
});
$('form.remember').on('submit'
work same as $('form.remember').submit(
but when you use $(document).on('submit','form.remember'
then it will also work for the DOM added later.
$('form.remember').on('submit'
工作方式相同,$('form.remember').submit(
但是当您使用时,$(document).on('submit','form.remember'
它也适用于稍后添加的 DOM。
回答by vitor_gaudencio_oliveira
I had a problem with the same symtoms. In my case, it turned out that my submit function was missing the "return" statement.
我遇到了同样的症状。就我而言,结果是我的提交函数缺少“返回”语句。
For example:
例如:
$("#id_form").on("submit", function(){
//Code: Action (like ajax...)
return false;
})
回答by Danial
The problem here is that the "on" is applied to all elements that exists AT THE TIME. When you create an element dynamically, you need to run the on again:
这里的问题是“on”适用于当时存在的所有元素。动态创建元素时,需要再次运行 on:
$('form').on('submit',doFormStuff);
createNewForm();
// re-attach to all forms
$('form').off('submit').on('submit',doFormStuff);
Since forms usually have names or IDs, you can just attach to the new form as well. If I'm creating a lot of dynamic stuff, I'll include a setup or bind function:
由于表单通常具有名称或 ID,因此您也可以附加到新表单。如果我要创建很多动态的东西,我将包含一个设置或绑定函数:
function bindItems(){
$('form').off('submit').on('submit',doFormStuff);
$('button').off('click').on('click',doButtonStuff);
}
So then whenever you create something (buttons usually in my case), I just call bindItems to update everything on the page.
所以无论何时你创建一些东西(在我的例子中通常是按钮),我只是调用 bindItems 来更新页面上的所有内容。
createNewButton();
bindItems();
I don't like using 'body' or document elements because with tabs and modals they tend to hang around and do things you don't expect. I always try to be as specific as possible unless its a simple 1 page project.
我不喜欢使用 'body' 或 document 元素,因为使用标签和模态,它们往往会四处游荡并做你意想不到的事情。我总是尽量具体,除非它是一个简单的 1 页项目。