0

在 Google 和 StackOverflow 上搜索数小时后,我找不到解决问题的方法。

假设场景:

html 内容存储在一个数组中,html_content

有一组带有绑定事件的div,控制id为#html_cntr的div中的内容,每个事件调用为$('#html_cntr').html(html_content[0])、$('#html_cntr').html( html_content[1]),依此类推。

例子:

<html>

<div id="html_cntr" style='width:100px;height:100px;background-color:#CCC;'>hello</div>
<div id="hover_area" style='width:100px;height:100px;background-color:#999;'>hover</div>

</html>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>    
<script>

html_content = Array();

html_content[0] = " \
<div id='test_area' style='width:100px;height:100px;background-color:#222;color:#FFF;'> \
click here \
</div> \
"

$('#hover_area').hover(function() {    
    $('#html_cntr').html(html_content[0]);
    alert('working');
});

// Does not work

$('#test_area').click(function() {
    alert('hello');
});

// Does not work

$('#test_area').on("click", function(){
    alert('hello');
});

// Does not work

$(document).ready(function(){
    $('#test_area').on("click", function(){
        alert('hello');
    });     
});

</script>

问题是,如何将事件绑定到使用 $('#html_cntr').html() 动态生成的内容?AFIAK on() 能够绑定不存在的元素或将来出现的元素,但无论我做什么它都不起作用。

这是jsfiddle上的片段

而且我也尝试过 onclick="function()",但没有运气。

感谢所有帮助,

谢谢!

4

2 回答 2

3

您需要使用事件委托

$('#html_cntr').on('click','#test_area',function() {
    alert('hello');
});
于 2013-05-28T18:03:05.677 回答
0

你也可以使用...

$('#html_cntr').delegate('#test_area','click',function() {
    alert('hello');
});
于 2013-05-28T18:33:44.333 回答