【问题标题】:how to bind events on ajax loaded elements如何在ajax加载的元素上绑定事件
【发布时间】:2012-08-20 02:44:38
【问题描述】:

我正在尝试通过 ajax 将内容加载到容器 (#ajax_content) 中。当我点击外部时,我希望能够关闭(隐藏)ajax 加载的内容(#ajax_content 中的所有内容)。但我想绑定里面元素的onClick。

HTML:

   <div id="wrapper"> 
      <div id="ajax_content">
      </div>
   </div>

通过 AJAX 加载的 HTML:

<button id="super_hello" >Click</button>

ajax 内容加载后的 HTML 将是

   <div id="wrapper"> 
      <div id="ajax_content">
          <button id="super_hello" >Click</button>
      </div>
   </div>

Javascript:

$(document).ready(function(){

    $('.ajax_link').click(function(event) {
       event.preventDefault();

       $.get($(this).attr('href'), function(data) {

            $('#ajax_content').html('');
            $('#ajax_content').append(data);

            $('#ajax_content').css({
                visibility: 'visible'
            });

        });

    });

    $('#ajax_content').click(function(event){

         event.stopPropagation();

    });

    $('#wrapper').click(function(){
        $('#ajax_content').hide();
        $('#ajax_content').html('');

        $(this).hide();
    });

});

    $(document).on("click","#super_hello",function(e){
        alert('clicked'); // I can't get this to work
    });

问题: 如果我评论

$('#ajax_content').click(function(event){

     event.stopPropagation();

}); 

事件绑定到 super_hello,但随后 ajax_content 内的任何点击都会传播到关闭 ajax_content 的包装器。

【问题讨论】:

    标签: jquery ajax events binding stoppropagation


    【解决方案1】:

    您可以直接在包装器的点击处理程序中过滤掉内容中的任何点击,例如:

    $('#wrapper').click(function(e) {
        if (!$(e.target).closest('#ajax_content').length) {
            $('#ajax_content').hide();
            $('#ajax_content').html('');
            $(this).hide();
        }
    });
    

    将检查是否存在具有#ajax_content ID 的父元素,包装器没有,但包装器内的内容确实有。

    另一方面,只要包装器和内容没有设置特定的大小,很可能内容会填满整个包装器,并且不会在包装器上注册任何点击,请参阅FIDDLE

    【讨论】:

    • 非常感谢,是的,实际上包装器设置为 100% 高度和 100% 宽度的绝对定位。糟糕的是,我没有包含所有的 CSS。
    • 出于某种原因,这个例子(尤其是小提琴)确实简洁地总结了绑定非常清楚。也许它今晚对我很有效,但它真的很有帮助!
    猜你喜欢
    • 1970-01-01
    • 2013-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-04
    • 1970-01-01
    相关资源
    最近更新 更多