JQuery .on()并没有将单击事件绑定到动态创建的元素[duplicate]

时间:2022-10-22 07:35:14

This question already has an answer here:

这个问题已经有了答案:

I have a textbox that dynamically adds an element when I press enter, and another that deletes the element when I click the delete button. The delete method works for any existing elements, but doesn't work for any elements that were dynamically inserted.

我有一个文本框,当我按enter时,它会动态地添加一个元素,还有一个文本框,当我点击delete按钮时,它会删除这个元素。delete方法适用于任何现有的元素,但不适用于任何动态插入的元素。

Here's the code:

这是代码:

$ ->
    # 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
    )

Any ideas? From what I've read, .on() should fix the issue of binding a click event to a dynamically generated element, but it doesn't seem to be working.

什么好主意吗?从我所读到的内容来看,.on()应该可以修复将单击事件绑定到动态生成的元素的问题,但它似乎不能工作。

1 个解决方案

#1


57  

this is wrong: $('.icon.remove').on('click'...

这是错误的:$(' .icon.remove ')。(“点击”……

this is right: $(document).on('click', '.icon.remove', function)

这是正确的:$(文档)。(“点击”、“.icon。删除”功能)

you can use any container instead of document (which is the most highlevel container).

您可以使用任何容器来代替文档(文档是*的容器)。

hope that helps

希望这有助于

#1


57  

this is wrong: $('.icon.remove').on('click'...

这是错误的:$(' .icon.remove ')。(“点击”……

this is right: $(document).on('click', '.icon.remove', function)

这是正确的:$(文档)。(“点击”、“.icon。删除”功能)

you can use any container instead of document (which is the most highlevel container).

您可以使用任何容器来代替文档(文档是*的容器)。

hope that helps

希望这有助于