You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用jQuery的$(this)选择器为动态创建的MainFolder元素追加div?

问题

我在运行时动态创建了两个class为MainFolder的div标签,代码如下:

<div class="MainFolder" style="padding-left: 20px; width: 200px; height: 23px;">
  <span class="glyphicon glyphicon-folder-close folder-icon"></span>Folder1<br>
</div>
<div class="MainFolder" style="padding-left: 20px; width: 200px; height: 23px;">
  <span class="glyphicon glyphicon-folder-close folder-icon"></span>Folder2<br>
</div>

请问如何在点击事件中使用jQuery的$(this)选择器为对应的元素追加div?

回答

嘿,这个问题我经常碰到,尤其是处理动态生成的DOM元素的时候,给你梳理下解决方案:

关键注意点

  • 因为你的.MainFolder是动态创建的,直接用$('.MainFolder').click()绑定事件是无效的——页面初始加载时这些元素还不存在,绑定的事件不会作用到它们身上。
  • 这时候必须用jQuery的事件委托,把事件绑定到一个已经存在的父元素(比如document或者更贴近的父容器)上,让它监听子元素的点击事件。

实现代码

// 使用事件委托绑定点击事件,确保动态创建的元素也能触发
$(document).on('click', '.MainFolder', function() {
  // $(this) 就是当前被点击的那个 .MainFolder 元素,精准定位!
  // 自定义你要追加的div内容,这里举个例子
  const appendedDiv = '<div style="padding-left: 30px; margin-top: 5px; color: #555;">这是追加的子内容</div>';
  
  // 给当前点击的文件夹追加div
  $(this).append(appendedDiv);

  // 可选:点击后切换文件夹图标(关闭→打开)
  $(this).find('.folder-icon').toggleClass('glyphicon-folder-close glyphicon-folder-open');
});

优化建议

  • 如果你的.MainFolder有固定的父容器(比如一个id为folderWrapper的div),建议把事件委托绑定到这个父容器上,比绑定到document性能更好:
    $('#folderWrapper').on('click', '.MainFolder', function() {
      // 同样的逻辑
      $(this).append('<div>追加内容</div>');
    });
    
  • 要是不想重复追加内容,可以在追加前加个判断,比如检查当前元素下有没有已追加的特定类名元素:
    $(document).on('click', '.MainFolder', function() {
      if (!$(this).find('.appended-item').length) {
        $(this).append('<div class="appended-item">只追加一次的内容</div>');
      }
    });
    

内容的提问来源于stack exchange,提问作者kevin Peter

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:41:33