【问题标题】:How do I apply a jquery Click event to dynamic list elements?如何将 jquery Click 事件应用于动态列表元素?
【发布时间】:2011-11-01 22:52:16
【问题描述】:

我当前的设置会加载一个动态列表,此时我通过 jquery 创建一个点击事件,如下所示:

$('#listReports li').click(function () {
    var selected = $(this).text();
    alert("List Item: " + selected);
});

我有代码可以让用户保存一个附加到列表中的报告。在我再次调用该函数之前,列表中的新项目不会触发点击事件。问题在于事件被触发两次的旧项目。

这是我如何附加列表项并再次调用然后函数:

            $("#save").click(function (e) {

                if ($("#reportParams li").size()> 0) {
                    var fileName = $('#reportFileName').val();

                    if (!fileName) {
                        alert("You must enter a file name!");
                    }
                    else {
                        $('#listReports').append('<li><a href="#">'+fileName+'</a></li>');

                        $('#listReports li').click(function () {
                            var selected = $(this).text();
                            alert("List Item: " + selected);
                        });
                    }
                }
            });

有没有办法只定义一次点击事件并让它影响添加到列表中的新项目?

【问题讨论】:

    标签: javascript jquery html


    【解决方案1】:

    .live()代替.click()

    $('#listReports li').live('click', function ()
    {
        var selected = $(this).text();
        alert("List Item: " + selected);
    });
    

    .delegate():

    $('#listReports').delegate('li', 'click', function ()
    {
        var selected = $(this).text();
        alert("List Item: " + selected);
    });
    

    【讨论】:

    • 效果很好! live和delegate有什么区别?一个比另一个更好吗?
    • .live() 在 jQuery 1.7+ 中已弃用。请改用.on()
    猜你喜欢
    • 2021-03-30
    • 2013-12-18
    • 2012-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多