JQuery - 为每个实例化的新 DOM 对象执行代码
我想知道这在 JQuery 中是否可行。
我有一些 Javascript 代码可以动态创建 DOM 对象,以响应用户操作。 其中一些 DOM 对象具有特定的结构 - 容器始终具有相同的“类”属性。
我想做的是,每次创建具有“X”类的 DOM 对象的新实例时,我都希望执行相同的 Javascript 代码片段。 该代码将向该 DOM 对象添加一个“onclick”事件。
不幸的是,我不能只将分配 onclick 的代码放在 document.Ready() 中,因为它绑定的对象是在 document.Ready() 执行很久之后动态创建的。
JQuery 是否允许您设置持久绑定,这些绑定将自动绑定到某种类型的 DOM 对象,即使它是动态生成的?
I'm wondering if this is possible in JQuery.
I have some Javascript code that creates DOM objects on the fly, in response to user actions. Some of those DOM objects are in a specific structure - the container always has the same "class" attribute.
What I'd like to do is, every time a new instance of a DOM object with class "X" is created, I want the same piece of Javascript code to execute. That code will add an "onclick" event to that DOM object.
Unfortunately I can't just put the code that assigns the onclick in document.Ready(), since the objects that it binds to are being created on the fly, long after document.Ready() has executed.
Does JQuery let you set up persistent bindings that will be automatically bound to a type of DOM object, even if it's generated on the fly?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我想我已经在 JQuery 文档中找到了我自己问题的答案,这令人惊讶。
http://docs.jquery.com/Events/live#typefn
在 jQuery 中添加1.3:将处理程序绑定到所有当前和未来匹配元素的事件(如单击)。 还可以绑定自定义事件。
I think I've found the answer to my own question, right in the JQuery documentation, surprisingly enough.
http://docs.jquery.com/Events/live#typefn
Added in jQuery 1.3: Binds a handler to an event (like click) for all current - and future - matched element. Can also bind custom events.
您是否看过名为 LiveQuery 的 jQuery 插件?
从 LiveQuery 文档页面:
Have you looked a the jQuery plugin called LiveQuery?
From the LiveQuery documentation page:
这过去被称为“实时”、“委托”,有时也被称为“绑定”。 这些现在已替换为“on”,但有一些注意事项,如下所述:Javascript 事件绑定持久性
This used to be covered by 'live', 'delegate', or sometimes 'bind'. These are now replaced with 'on' however there are some caveats as discussed here: Javascript event binding persistence
在 jQuery 核心中不可能(正如您可能已经通过参考某些插件的其他答案意识到的那样)...如果您不一定需要像
livequery
这样的东西的所有功能,这可能是一个非常简单的任务支持它们的浏览器 - 使用 DOM level 2 事件 - 'DOMNodeInserted':
http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-eventgroupings-mutationevents
Not possible in jQuery core (as you've probably realized with other answers referring to some plugins)... this can be a very simple task if you dont necessarily need all the functionality of something like
livequery
For the browsers that support them - use the DOM level 2 event - 'DOMNodeInserted':
http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-eventgroupings-mutationevents