简体   繁体   中英

JQuery bind click event to html() generated content

After hours of search on Google and StackOverflow I could not find a solution to my problem.

Suppose the scenario:

The html content is stored in a array, html_content

There is a set of divs with binded events that controls the content in div with id #html_cntr, each event call being $('#html_cntr').html(html_content[0]), $('#html_cntr').html(html_content[1]), so on.

Example:

<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>

The problem is, How do I bind an event to content dynamically generated using $('#html_cntr').html()? AFIAK on() is capable of binding non-existent elements or elements that appears in the future, but It didn't work no matter what I do.

Here is the snippet on jsfiddle

And I've also tried onclick="function()", but with no luck.

All help is appreciated,

Thanks!

You need to use event delegation

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

you can also use...

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM