jQuery中的嵌套点击 [英] Nested click in jQuery

查看:65
本文介绍了jQuery中的嵌套点击的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个DIV,当单击它时,它将在其内部添加另一个DIV.然后,如果我单击新添加的DIV,它将删除它.

I have a DIV that when click on it, it will add another DIV inside itself. Then if I click the newly added DIV it will remove it.

HTML

<div id="container"></div>

jQuery

$('#container').on('click', function(e){

  // Add other DIV
  $( this ).append('<div class="other">XYZ</div>');

  e.stopPropagation();

  // Remove other DIV
  $('div.other').bind('click', function(event){

    $( this ).remove();

    event.stopPropagation();

  });

});

如果我打算有很多子DIV,这种方法的效率如何?

How efficient is this method if I plan to have to lot of child DIVs?

推荐答案

在另一个事件触发时附加事件可能会导致一些意外的副作用,并使您的DOM遭受内存泄漏.

Attaching events when another event fires will likely cause some unintentional side effects, and subject your DOM to memory leaks.

一般规则是,附加处理程序一次,并经常运行.

As a general rule, attach handlers once, run often.

$(document)
    .on('click', '#container', function(e) {
        // Add other DIV
        $(this).append('<div class="other">XYZ</div>');
    })
    .on('click', 'div.other', function(e) {
        $(this).remove();
        e.stopPropagation();
    });

这篇关于jQuery中的嵌套点击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆