如何让一个事件监听器处理通过javascript添加到我的html的元素?

时间:2013-04-26 07:19:52

标签: javascript jquery event-handling

我正在通过javascript向我的文档中添加一些HTML。我还通过这个javascript函数为我的HTML添加了一个按钮。我希望这个按钮有一个事件监听器,但这似乎不适用于使用javascript添加的元素。有可能解决这个问题吗?

我的js:

$('#content-overview li').on('click',function(){

            // Clear previous videos
            $('.content-overview-row').remove();

            // Insert new video
            var vimeoId = $(this).data('vimeo');            
            var html = '<li class="content-overview-row"><div class="content-overview-video"><iframe src="http://player.vimeo.com/video/'+vimeoId+'" width="950" height="534"></iframe><a id="close-video"></a></div></li>';

            // Find end of row and insert detailed view
            var nextRow = $(this).nextAll('.first-in-row:first');

            if(nextRow.is('li')){
                nextRow.before(html);   
            }
            else{
                //last row
                if($(this).hasClass('first-in-row'))
                {
                    //first item clicked in last row
                    $(this).before(html);
                }
                else{
                    $(this).prevAll('.first-in-row:first').before(html);
                }
            }           

            return false;

            $('#close-video').click(function() {
                console.log("works");
            });
    });

close-video是我正在谈论的关闭按钮。

1 个答案:

答案 0 :(得分:2)

您需要将click事件绑定到加载页面时存在于DOM中的元素,并委托动态添加的元素,如下所示:

$(document).on('click', '#close-video', function() {
   ...
});

您应该为距离document最近的元素更改#close-video,这样就不必冒泡到document

此外,您在returning false;点击处理程序之前是#close-video,因此无论如何都不会执行代码。将其移到#content-overview li点击处理程序之外。