繁体   English   中英

当jQuery元素被附加到DOM时,触发OnAppend事件

[英]Fire OnAppend event for jQuery element when it gets appended to the DOM

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

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

生成器的示例代码:

function getControl(controlParams){
    var $control = $('<div/>');
    $control.applyCustomScrollBar(); //Not appended to DOM yet, so doesnt work
    return $control;
}

消费者的示例代码:

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,您需要触发自定义事件,请尝试以下操作:

$("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/

希望能帮助到你

你可以在不使用MutationObserver jquery的情况下做到这一点

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

// 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();

来源: devdocs.io这篇博客文章中获取它

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM