我有一个文本框,在按下回车键时会动态地添加一个元素,还有一个在我点击删除按钮时删除该元素的功能。但是删除方法适用于所有已存在的元素,却无法作用于动态插入的元素。
这是代码:
这是代码:
$ ->
# 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 = '<a class="item" data-path="' + response.path + '" data-stock="' + response.symbol + '">'+ response.symbol + '<i class="icon remove"></i></a>'
$('#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()应该可以解决将点击事件绑定到动态生成元素的问题,但似乎并没有起作用。
on
可以解决问题。例如:$(container).on('click', '.icon.remove', function(){...
这里的container
是包含这些元素的容器选择器,并且随时可用。请注意,翻译尽可能保持原意和简洁,不提供额外的信息或解释。 - PSL