Javascript 当jQuery元素被附加到DOM时,为其激发OnAppend事件

Javascript 当jQuery元素被附加到DOM时,为其激发OnAppend事件,javascript,jquery,html,Javascript,Jquery,Html,我编写了一些代码来生成自定义控件。代码返回一个jQuery元素,调用方将该jQuery元素附加到DOM中。 我在生成器代码中将自定义滚动条应用于控件,但由于元素尚未附加到DOM中,因此未应用该滚动条 我的问题是:是否存在onAppend事件或类似事件,以便在将元素附加到DOM时应用自定义滚动条 生成器的示例代码: function getControl(controlParams){ var $control = $('<div/>'); $control.apply

我编写了一些代码来生成自定义控件。代码返回一个jQuery元素,调用方将该jQuery元素附加到DOM中。 我在生成器代码中将自定义滚动条应用于控件,但由于元素尚未附加到DOM中,因此未应用该滚动条

我的问题是:是否存在onAppend事件或类似事件,以便在将元素附加到DOM时应用自定义滚动条

生成器的示例代码:

function getControl(controlParams){
    var $control = $('<div/>');
    $control.applyCustomScrollBar(); //Not appended to DOM yet, so doesnt work
    return $control;
}
想做一些类似于:

function getControl(controlParams){
    var $control = $('<div/>');
    $control.onAppend(function(){
        $(this).applyCustomScrollBar();
    });

    return $control;
}
函数getControl(controlParams){
变量$control=$('');
$control.onAppend(函数(){
$(this.applyCustomScrollBar();
});
返回$control;
}

要检测元素是否已添加到DOM中,需要触发自定义事件,请尝试以下操作:

$("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");​
$(“body”)。关于(“appended”、“div”函数(事件){
//事件将元素追加到DOM中后,是否执行任何操作
$(this.css(“背景”、“蓝色”);
});
$("", {
id:“一些控制”,
文本:“示例控件”
}).附录(“主体”)。触发器(“被上诉”);​
小提琴示例:


希望对您有所帮助

您可以使用
MutationObserver在没有jquery的情况下实现这一点

MutationObserver
为开发人员提供了一种对DOM中的更改做出反应的方法。它被设计为DOM3事件规范中定义的突变事件的替代品


资料来源:从Afaik获得的,没有这样的事件。DOM中的更改会触发变异事件,但是如果您可以控制代码,您可以创建一个自定义事件,并在每次您自己添加元素时触发它,因为这会容易得多,跨浏览器.DOM变异事件将是实现这一点的一种方法,但是您最好只创建自己的自定义事件,并(假设您使用某种外部API构建此事件)将其公开以供使用。@adeneo:这不是一个选项。可能有成吨的消费者。因此,我不能告诉消费者要一直启动事件。我刚才想到的另一个想法是修改jQueryAppend方法来触发此事件。但这看起来又是一团糟。每次更新时,我都必须更新此事件的jquery文件。由于追加是同步的,因此实际上没有内置事件或回调,通常,如果您以正确的顺序构造代码,您就不需要这样的事件或回调!这个答案应该被接受,因为它正是我所需要的
$("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");​
// select the target node
var target = document.getElementById('some-id');

// create an observer instance
var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    console.log(mutation.type);
  });    
});

// configuration of the observer:
var config = { attributes: true, childList: true, characterData: true };

// pass in the target node, as well as the observer options
observer.observe(target, config);

// later, you can stop observing
observer.disconnect();