【问题标题】:JQuery bind click event to html() generated contentJQuery 将点击事件绑定到 html() 生成的内容
【发布时间】: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


    【解决方案1】:

    你需要使用事件委托

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

    【讨论】:

    • @WilliamYang .. 欢迎您!
    • 你也可以用$('#html_cntr')代替$(document)
    【解决方案2】:

    你也可以使用...

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

    【讨论】:

      猜你喜欢
      • 2019-05-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-04
      • 2023-04-04
      • 2012-03-24
      • 1970-01-01
      • 2017-04-14
      相关资源
      最近更新 更多