JQuery .on()没有将点击事件绑定到动态创建的元素

我有一个文本框,当我按Enter键时动态添加一个元素,另一个文本框在我单击删除按钮时删除该元素。 delete方法适用于任何现有元素,但不适用于动态插入的任何元素。

这是代码:

$ -> # AJAX to add a new stock $("#add-symbol").keypress (e) -> if e.which == 13 url = $(this).data('url') name = $(this).val() $.ajax url: url type: "POST" data: { user_id: $('#info').data('user-id'), name: name } success: (response) -> if response.status == 200 new_element = ''+ response.symbol + '' $('#symbols').append(new_element) $('#add-symbol').val('') else #deal with errors # AJAX to delete stocks $('.icon.remove').on('click', (e) -> console.log('click click') $parent = $($(this).parent().get(0)) stock = $parent.data('stock') user_id = $("#info").data('user-id') url = $parent.data('path') $.ajax url: url type: "DELETE" data: { user_id: user_id, name: stock } success: (response) -> if response.status == 200 $parent.remove() else # deal with errors ) 

有任何想法吗? 根据我的阅读,.on()应该解决将click事件绑定到动态生成的元素的问题,但它似乎不起作用。

这是错的: $('.icon.remove').on('click'...

这是正确的: $(document).on('click', '.icon.remove', function)

您可以使用任何容器而不是文档(这是最高级别的容器)。

希望有所帮助