jQuery“on create”事件为动态创建的元素 [英] jQuery "on create" event for dynamically-created elements
问题描述
我需要能够动态创建< select>
元素,并将其转换为jQuery .combobox()
。这应该是元素创建事件,而不是一些点击事件在这种情况下,我可以只使用jQuery .on()
。
这样的东西是否存在?
$(document).on(create,select ,function(){
$(this).combobox();
}
我不愿意使用livequery,因为它非常过时。
UPDATE 提到的select / combobox通过ajax加载到因此问题 - 我只能使用colorbox onComplete
启动组合框,但是在更改一个组合框时,必须动态创建另一个选择/组合框,因此,需要一个更通用的方法来检测元素的创建( select
在这种情况下)。
UPDATE2 要进一步尝试解释问题 - 我有递归创建的 select / combobox
元素,中还有很多启动代码。 combobox()
,因此如果我使用经典方法,例如在 @ bipen的回答,我的代码会膨胀到疯狂的水平。
DOMNodeInserted
在DOM变异中有一个void,并且没有解决这个问题的方法。 您可以 on
DOMNodeInserted
事件,以获取添加到
$('body')。on('DOMNodeInserted','select',function
// $(this).combobox();
});
$('< select>')。appendTo('body');
$('< select>')。appendTo('body');
在这里挑战:http://jsfiddle.net/Codesleuth/qLAB2/3/
编辑:阅读后我只需要仔细检查 DOMNodeInserted
不会导致跨浏览器的问题。 2010年的这个问题表明IE不支持该事件,因此,如果可以,请测试它。
请参阅: [link] 警告! DOMNodeInserted事件类型在本规范中定义以供参考和完整性,但此规范不赞成使用使用此事件类型。
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();
}
I'm reluctant to use livequery, because it's very outdated.
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 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 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.
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');
Fiddled here: http://jsfiddle.net/Codesleuth/qLAB2/3/
EDIT: 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.
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“on create”事件为动态创建的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!