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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19371141/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 23:48:39  来源:igfitidea点击:

JQuery .on() isn't binding click events to dynamically created elements

javascriptjqueryruby-on-railscoffeescript

提问by chintanparikh

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 方法适用于任何现有元素,但不适用于任何动态插入的元素。

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() 应该解决将点击事件绑定到动态生成的元素的问题,但它似乎不起作用。

回答by geevee

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

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

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

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

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

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

hope that helps

希望有帮助