【发布时间】:2013-05-23 19:25:20
【问题描述】:
在 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的sn-p
我也尝试过 onclick="function()",但没有成功。
感谢所有帮助,
谢谢!
【问题讨论】:
标签: php jquery html web-applications