ajax之后不触发jquery事件

ajax之后不触发jquery事件,jquery,ajax,Jquery,Ajax,我有下面的js,在ajax附加内容后事件不会触发 $(".item").mouseenter(function(){ $(this).children('.delete').show(); }); $(".item").mouseleave(function(){ $(this).children('.delete').hide(); }); $(".delete").click(function(){ $(this).parent().hide(); }); $("#add").

我有下面的js,在ajax附加内容后事件不会触发

$(".item").mouseenter(function(){ $(this).children('.delete').show(); });

$(".item").mouseleave(function(){ $(this).children('.delete').hide(); });

$(".delete").click(function(){
    $(this).parent().hide(); });

$("#add").click(function(){
  action = 'addItem';
  $.ajax({
    type: "POST",
    url: "/echo/json/",
    data: 'action='+action,
    cache: false,
    success: function(json){
        $(".main").append('<div class="item"><div class="content"> content new </div><div class="delete"> delete </div></div>');
    }
  });
});
$(“.item”).mouseenter(函数(){$(this).children('.delete').show();});
$(“.item”).mouseleave(function(){$(this).children('.delete').hide();});
$(“.delete”)。单击(函数(){
$(this.parent().hide();});
$(“#添加”)。单击(函数(){
动作='附加项';
$.ajax({
类型:“POST”,
url:“/echo/json/”,
数据:“action=”+action,
cache:false,
成功:函数(json){
$(“.main”).append('content new delete');
}
});
});
请在以下网址查看JSFIDLE

如何确保无论我添加了多少项,mouseenter和mouseleave事件都会被触发?

您需要使用以下选项:

事件委派是指使用事件传播(冒泡)在DOM中处理事件的过程,其级别高于事件发生的元素。它允许我们为现在或将来存在的元素附加单个事件侦听器

假设您的
.main
元素不是动态创建的,则此事件侦听器将分配给
.main
元素,并且仅在该特定子体发生事件时才会触发。

您需要将事件绑定到动态添加的元素:

事件委派允许我们将单个事件侦听器附加到父元素,该事件侦听器将为与选择器匹配的所有子体触发,无论这些子体现在存在还是将来添加

或者
$('.main').on('mouseenter', '.item', function() {
    ...
});
$(".main").on('click','.delete',function(){
   $(this).parent().hide();
});