事件绑定到动态创建的元素

Event bind to the dynamically created elements

本文关键字:元素 创建 动态 绑定 事件      更新时间:2023-09-26

我有一个文本框#search_text。在keyup上,我创建了一个div#sresult_container,并将其附加到某个div到div#sresolt_container。当这个容器显示在画布上时,我尝试将click和mouseover事件绑定到div#sresult_container。我试着遵循代码,但不起作用。我该怎么办?

$("#search_text").keyup(function(e) {
    if (e.which != 40 && e.which != 38) {
        $("#search").removeAttr('disabled');
        $.post('http://www.allinone.com', {
            Search: sVal
        }, function(data) {
            $sresult_container = $('<div id="sresult_container"></div>');
            //somecode which create another divs and append to the $sresult_container
        })
    }
    $('#sresult_container').bind({
        click: function(e) {
            //some code  
            },
            mouseover: function(e) {
                //some code
            }
        });
    });
$('#someParent').on('click', '.someChildSelector', function(e){
});

侦听与指定(即.someChildSelector)选择器匹配的、冒泡到#someParentclick事件。

因此,源自您附加的任何子元素的事件都将被上述处理程序捕获。

您可以使用"live"功能来完成此任务。

$('#sresult_container').live('click', function() {
    alert('hello from binded function call');
});