将事件处理程序添加到新创建的元素

我正在尝试将新元素添加到有序列表中,并为其删除链接:

$('#list ol').append('
  • ' + label + ' [remove]
  • ');

    但这不起作用:

     $('a[href^="#remove"]').on('click', function(event){ alert('Removing: '+$(this).attr('href').substr(8)); event.preventDefault(); }); 

    知道为什么吗?

    在jQuery标记中包装新元素并在那时应用事件处理程序。 与使用有些复杂的jQuery选择器在元素已插入DOM后分配事件处理程序相比,这是一种更简洁,更有效的方法:

     //this line will create your element in memory, but not insert it to the DOM var newElmt = $('
  • ' + label + ' [remove]
  • '); //you can apply jQuery style event handlers at this point newElmt.on('click',function(e) { alert('Removing: '+$(this).attr('href').substr(8)); event.preventDefault(); }); //insert the element as you were before $('#list ol').append(newElmt);
     $('#list').on('click', 'a[href^="#remove"]', function(event){ alert('Removing: '+$(this).attr('href').substr(8)); event.preventDefault(); }); 

    当你动态附加li ,你需要使用.on()作为委托处理程序进行委托事件处理。