jQuery“在创建时"动态创建元素的事件 [英] jQuery "on create" event for dynamically-created elements
问题描述
我需要能够动态创建 元素并将其转换为 jQuery
.combobox()
.这应该是元素创建事件,而不是一些点击"事件,在这种情况下我可以只使用 jQuery .on()
.
I need to be able to dynamically create <select>
element and turn it into jQuery .combobox()
. This should be element creation event, as opposed to some "click" event in which case I could just use jQuery .on()
.
那么存在这样的东西吗?
So does something like this exist?
$(document).on("create", "select", function() {
$(this).combobox();
}
我不太愿意使用 livequery,因为它已经过时了.
I'm reluctant to use livequery, because it's very outdated.
UPDATE 提到的选择/组合框通过 ajax 加载到 jQuery 颜色框(模态窗口)中,因此问题 - 我只能使用 colorbox onComplete
启动组合框,但是在更改一个组合框时,必须动态创建另一个选择/组合框,因此我需要一种更通用的方法来检测元素的创建(在本例中为 select
).
UPDATE The mentioned select/combobox is loaded via ajax into a jQuery colorbox (modal window), thus the problem - I can only initiate combobox using colorbox onComplete
, however on change of one combobox another select/combobox must be dynamically created, therefor I need a more generic way to detect creation of an element (select
in this case).
UPDATE2 尝试进一步解释问题 - 我有 select/combobox
递归创建的元素,在 .combobox()
,因此如果我使用经典方法,例如 @bipen 的答案,我的代码会膨胀到疯狂水平.希望这能更好地解释问题.
UPDATE2 To try and explain the problem further - I have select/combobox
elements created recursively, there is also a lot of initiating code inside .combobox()
, therefore if I used a classic approach, like in @bipen's answer, my code would inflate to insane levels. Hope this explains the problem better.
UPDATE3 谢谢大家,我现在明白自从 DOMNodeInserted
被弃用后,DOM 突变中留下了一个空白,这个问题没有解决方案.我只需要重新考虑我的申请.
UPDATE3 Thanks everyone, I now understand that since deprecation of DOMNodeInserted
there is a void left in DOM mutation and there is no solution to this problem. I'll just have to rethink my application.
推荐答案
您可以on
DOMNodeInserted
事件,用于获取您的代码将其添加到文档时的事件.
You can on
the DOMNodeInserted
event to get an event for when it's added to the document by your code.
$('body').on('DOMNodeInserted', 'select', function () {
//$(this).combobox();
});
$('<select>').appendTo('body');
$('<select>').appendTo('body');
在这里摆弄:http://jsfiddle.net/Codesleuth/qLAB2/3/
在阅读之后,我只需要仔细检查 DOMNodeInserted
不会导致跨浏览器出现问题.2010 年的这个问题表明 IE 不支持该事件,因此如果可以,请对其进行测试.
after reading around I just need to double check DOMNodeInserted
won't cause problems across browsers. This question from 2010 suggests IE doesn't support the event, so test it if you can.
请参阅此处:[link] 警告!DOMNodeInserted 事件类型在本规范中定义以供参考和完整性,但本规范 弃用这种事件类型.
See here: [link] Warning! the DOMNodeInserted event type is defined in this specification for reference and completeness, but this specification deprecates the use of this event type.
这篇关于jQuery“在创建时"动态创建元素的事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!