[英]jQuery without adding additional plugins: trigger event when an element with a specific class is added to the DOM
使用jQuery:我想在具有特定類的元素添加到頁面時進行偵聽。 當這個事件發生時,我會做一些邏輯(在這個例子中由一個警告消息表示)。
$('button').on('click', function(){ $(this).after('<p class="foobar">Element added</p>'); }); //Doesn't work, but shows what I am going after. I want to listen for when ap element with the class 'foobar' gets added to the DOM. When this happens: I want to be able to throw an alert. // $('p.foobar').on('when_it_is_added', function(){ // alert("I have been added to the dom"); // });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button>click to add ap element </button>
關鍵細節是我需要在這個動態<p>
元素上使用事件監聽器,並且我需要在DOM中加載事件后觸發該事件。
實現這一目標的最快方法是創建自己的事件並在將“p”元素附加到dom后自行觸發...或者在附加到dom后執行另一個函數。
例1:
//Here I'm going to create an event 'tagAdded' and trigger it after appending element..
$('button').on('click', function(){
$(this).after('<p class="foobar">Element added</p>').trigger('tagAdded');
});
然后
$('button').on('tagAdded', function(){
//do something
})
要么
追加后調用方法..
例2:
$('button').on('click', function(){
$(this).after('<p class="foobar">Element added</p>');
someMethod();
});
function someMethod(){
var newPtAG = $('body').find('.foobar');
}
鏈接: http : //codepen.io/theConstructor/pen/GqpQqY
希望這可以幫助
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.