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

Javascript 事件绑定到动态创建的元素,javascript,jquery,Javascript,Jquery,我有一个文本框,搜索文本。在keyup上,我创建一个div#sresult_容器,并将其附加到一些div to div#sresult_容器。当该容器显示在画布上时,我尝试将click and mouseover事件绑定到div#sresult_容器。我尝试下面的代码,但这不起作用。我该怎么做 $("#search_text").keyup(function(e) { if (e.which != 40 && e.which != 38) { $("#se

我有一个文本框,搜索文本。在keyup上,我创建一个div#sresult_容器,并将其附加到一些div to div#sresult_容器。当该容器显示在画布上时,我尝试将click and mouseover事件绑定到div#sresult_容器。我尝试下面的代码,但这不起作用。我该怎么做

$("#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
            }
        });
    });
$(“#搜索_文本”).keyup(函数(e){
如果(e.which!=40&&e.which!=38){
$(“#搜索”).removeAttr('disabled');
$.post($)http://www.allinone.com', {
搜索:sVal
},函数(数据){
$sresult_container=$('');
//创建另一个div并附加到$sresult\u容器的代码
})
}
$(“#sresult_容器”).bind({
点击:功能(e){
//一些代码
},
鼠标悬停:功能(e){
//一些代码
}
});
});
侦听出现与指定(即
.someChildSelector
)选择器匹配的
#someParent
事件的
单击

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

您可以使用“”函数执行此任务

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

不,我的朋友。从jQuery1.7开始,不推荐使用
.live()
方法。小心
.live()
方法不可用。使用
.on()
'.delegate()
代替。可能重复@RVSharepoint:这不是重点。报复性否决投票对任何人都没有帮助。这就像是说——没有人会更新他们的jQuery版本。。这对一些人也很有帮助:)@RVSharepoint:这就是为什么他选择了你的答案,我想:)我不同意这是最好的解决方案,因此,我选择了否决投票。但这并不能解释你的反对票。违背了这个社区的精神,我的朋友。祝您愉快。但我也在最新的jQuery1.8中使用了live函数。这对我来说很好。祝您愉快:)
$('#sresult_container').live('click', function() {
    alert('hello from binded function call');
});