当它被附加到DOM时,为jQuery元素启动OnAppend事件 [英] Fire OnAppend event for jQuery element when it gets appended to the DOM
问题描述
我写了一些代码来生成自定义控件。代码返回一个jQuery元素,调用者将这个jQuery元素附加到DOM。
我将自定义滚动条应用于生成器代码中的控件,但由于该元素尚未附加到DOM,因此无法应用。
I wrote some code to generate custom controls. The code returns a jQuery element and the caller appends this jQuery element to the DOM. I apply a custom scrollbar to the control in the generator code, but it doesn't get applied as the element has not been appended to the DOM yet.
我的问题:是否有任何onAppend事件或类似事件,以便在元素附加到DOM时应用自定义滚动条?
My question: Is there any onAppend event or something like that, so that I apply the custom scrollbar at the time when the element has been appended to the DOM?
示例代码生成器:
Sample code for generator:
function getControl(controlParams){
var $control = $('<div/>');
$control.applyCustomScrollBar(); //Not appended to DOM yet, so doesnt work
return $control;
}
消费者的示例代码:
Sample code for consumer:
var $control = getControl(controlParams);
$("body").append($control); //Appending to DOM now
想做类似的事情:
function getControl(controlParams){
var $control = $('<div/>');
$control.onAppend(function(){
$(this).applyCustomScrollBar();
});
return $control;
}
推荐答案
添加到DOM,你需要触发一个自定义事件,试试这个:
To detect if element has been added to the DOM, you need to trigger a custom event, try this:
$("body").on("appened", "div", function(event){
//event after append the element into DOM, do anything
$(this).css("background", "blue");
});
$("<div/>", {
id: "some-control",
text: 'Example Control'
}).appendTo("body").trigger("appened");
小提琴示例:http://jsfiddle.net/uudDj/1/
希望它有帮助
这篇关于当它被附加到DOM时,为jQuery元素启动OnAppend事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!