【问题标题】:Do something after .html() has been fired在 .html() 被触发后做一些事情
【发布时间】:2017-11-06 10:32:53
【问题描述】:

我将页面上另一个 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');
});

任何帮助将不胜感激;)

【问题讨论】:

  • 我无法看到任何带有 box-grid__item-content-popup 类的 html 元素?
  • 在 chrome 控制台中测试这段代码:$('.box-grid__item-content-popup').removeClass('show');如果此命令有效,则 close-btn onclick 无效

标签: javascript jquery html


【解决方案1】:

由于您是动态插入 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/ 上的委托事件部分

【讨论】:

  • 非常感谢您的帮助:)
【解决方案2】:

我假设您在插入 html 之前有您的 .click 代码。 你可以做的是重写你的函数,让它在.box-grid__item 上触发,然后在上面放置一个选择器。

$(".box-grid__item").on("click", ".close-btn", function(){
      $('.box-grid__item-content-popup').removeClass('show');
 });

【讨论】:

    【解决方案3】:
    // 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'})
    

    fiddle

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-01
      • 1970-01-01
      • 2020-03-25
      • 1970-01-01
      • 1970-01-01
      • 2012-03-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多