Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
375 views
in Technique[技术] by (71.8m points)

javascript - jQuery "on create" event for dynamically-created elements

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 (selectin 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.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...