[英]Do something after .html() has been fired
我正在將頁面上另一個div的HTML注入div,然后添加一個.show類,如下所示:
var $boxItem = $('.box-grid__item'),
$htmlData = $($boxItem).find('.box-grid__item-content').html();
$boxItem.click(function () {
$('.box-grid__item-content-popup').html($htmlData).addClass('show');
});
注入的HTML是:
<div class="close-btn" aria-label="Close">
<span></span>
<span></span>
</div>
<h2 class="box-grid__item-content-heading">Name and Surname</h2>
<p class="box-grid__item-content-title">Title</p>
<p class="box-grid__item-content-text">Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.</p>
這按預期工作,但現在我想刪除.show。 我試過這個,但它不會觸發:
$('.close-btn').click(function () {
$('.box-grid__item-content-popup').removeClass('show');
});
任何幫助都感激不盡 ;)
由於您是動態插入HTML,因此您的事件處理程序應類似於:
$('.box-grid__item-content-popup').on("click", '.close-btn', function () {
$('.box-grid__item-content-popup').removeClass('show');
})
這意味着將捕獲冒泡到.box-grid__item-content-popup
的事件,但是當在.close-btn
或其中一個后代上觸發事件時,處理程序將觸發。
參考:請參閱http://api.jquery.com/on/上的委派活動部分
我假設你在插入html之前有你的.click
代碼。 您可以做的是重寫您的函數,因此它會在.box-grid__item
上觸發,然后在其上放置一個選擇器。
$(".box-grid__item").on("click", ".close-btn", function(){
$('.box-grid__item-content-popup').removeClass('show');
});
// create a reference to the old `.html()` function
var htmlOriginal = $.fn.html;
// redefine the `.html()` function to accept a callback
$.fn.html = function(html,callback){
// run the old `.html()` function with the first parameter
var ret = htmlOriginal.apply(this, arguments);
// run the callback (if it is defined)
if(typeof callback == "function"){
callback();
}
// make sure chaining is not broken
return ret;
}
// test it all works as expected (including chaining)
$("#mything").html("<div>My Thing</div>",function(){
console.log("Just did my thing");
}).css({color: 'red'})
看小提琴
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.