JQuery .on() 没有将点击事件绑定到动态创建的元素 [英] JQuery .on() isn't binding click events to dynamically created elements

查看:26
本文介绍了JQuery .on() 没有将点击事件绑定到动态创建的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

代码如下:

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

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.

推荐答案

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

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

您可以使用任何容器代替文档(这是最高级别的容器).

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

希望对你有帮助

这篇关于JQuery .on() 没有将点击事件绑定到动态创建的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆