[英]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.