首页 > 解决方案 > 尽管 $(document).on('click', '.foo', function) 方法,但克隆元素上的单击事件不起作用

问题描述

我有以下 div

<div class = 'step'></div>

附加到一个click()事件,.step如果它没有,则添加一个类,反之亦然:

$(".step").click(function(){
  if ($(this).hasClass('stepLit')) {
    $(this).removeClass('stepLit')
  } else {
    $(this).addClass('stepLit')
  }
})

我像这样克隆 div:

var step = $(".step").clone()

并附加它:

$(step).appendTo('#foo')

现在,如果我想使用 class 将点击事件附加到所有现有和动态生成的 HTML 元素'.step',我必须使用以下.on方法:

$(document).on('click', '.step', function(){...})

但是当我单击我的克隆+附加元素时,事件(添加/删除 lit 类)仍然没有发生。这是否与this我的点击函数中的关键字现在不指代被点击的 div 而是指文档这一事实有关?

标签: htmljqueryappendclick

解决方案


我为您创建了一个演示,看看这是否适合您。

$(document).on('click', '.step', function(){
  if ($(this).hasClass('stepLit')) {
    $(this).removeClass('stepLit');
    $(this).find('span').text('step');
  } else {
    $(this).addClass('stepLit');
    $(this).find('span').text('stepLit');
  }
});



$(document).on('click', '.clone', function(){
  console.clear();
  let $step = $(".step:first").clone()
  console.log($step);
  $step.appendTo("#foo");
});
div{
  height: 50px;
}

.step{
  background: aquamarine;
}

.stepLit{
  background: bisque;
}

#foo{
  background: burlywood;
  margin: 5px 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class='step'>
  <span>step</span><br>
  <button class="clone">Clone</button>
</div>

<div id="foo"></div>


推荐阅读