.on()绑定在触发器('create')后不起作用(.on() bindings not working after trigger('create'))

在我正在构建的JQM(1.3.0)应用程序中,我使用“on”将所有提交按钮绑定到单击事件,意图是现在和将来所有提交按钮都将绑定此事件。 我在$(document).ready()中进行这些绑定,因为我觉得它只需要调用一次......永远。

我用一些内容更新JQM 面板 ,并在该内容上调用.trigger('create')。 应该发生的是,新创建的提交按钮应该在单击时触发绑定的单击事件,但事实并非如此。

这是一个小提示,展示了我想要实现的目标。 在演示中,每当您单击提交按钮时,消息框都应显示“Clicked”...不幸的是,它只发生在第一个元素上。

$(function(){ $('input[type="submit"]').on('click', function(e){ $('#msg').append('<div>Clicked</div>'); $('#panel').html('<input type="submit" value="New Button">').trigger('create'); }); });

我在这里错误地使用.on()吗? 我想我可以将所有绑定填充到函数中,然后在调用.trigger('create')时调用该函数......但这似乎效率低下。

In a JQM (1.3.0) app that I'm building, I bind all my submit buttons to a click event using "on" with the intent that all submit buttons now and in the future will have this event bound. I'm doing these bindings in the $(document).ready() because I figure it only needs to be called once...ever.

I update a JQM panel with some content and call .trigger('create') on that content. What should happen is that the newly created submit button should trigger the bound click event when clicked, but it doesn't.

Here's a fiddle demonstrating what I'm trying to achieve. In the demo, the message box should display "Clicked" whenever you click a submit button...unfortunately, it only happens with the first element.

$(function(){ $('input[type="submit"]').on('click', function(e){ $('#msg').append('<div>Clicked</div>'); $('#panel').html('<input type="submit" value="New Button">').trigger('create'); }); });

Am I using .on() incorrectly here? I guess I could stuff all my bindings into a function, and then call that function whenever .trigger('create') is called...but that seems inefficient.

最满意答案

使用.on方法绑定事件有两种方法。 一个是使用事件委托,它将事件绑定到更高级别的元素(如果需要,一直到document ,但越接近越好)然后当事件冒泡时它会监听它并且如果它匹配传入的选择它发射。 使用.on的第二种方法是将其直接绑定到元素而不使用委托。

您正在使用.on方式的第二个版本,但您想要的是使用第一个版本(委托版本)。

例如,您可以执行以下操作代替当前代码

$(function(){ $('#someParentElement').on('click','input[type="submit"]', function(e){ $('#msg').append('<div>Clicked</div>'); $('#panel').html('<input type="submit" value="New Button">').trigger('create'); }); });

There are two ways to bind events using the .on method. One is using event delegation which works binding the event to a higher level element (all the way up to the document if necessary, but the closer the better) and then when an event bubbles up it listens to it and if it matched the passed in selector it fires. The second way to use .on is to bind it directly to the element without using delegation.

You are using the second version of .on way, but what you want is to use the first (delegation version).

For example instead of your current code you would do something like the following

$(function(){ $('#someParentElement').on('click','input[type="submit"]', function(e){ $('#msg').append('<div>Clicked</div>'); $('#panel').html('<input type="submit" value="New Button">').trigger('create'); }); });

更多推荐