views:

74

answers:

3

I have a code chunk of html:

<div id="chunk-1" class="chunk">  
    <div class="chunkText">Text<div>  
    <button class="addChunk">Click Me</button>  
</div>

<script>

$(".addChunk").click(function(){create_chunk(this.parentNode)})

function create_chunk(after_this){
    $(after_this).after(chunk_html)
    var i = 0
    $("div.chunk").each(function(){$(this).attr('id', "chunk-" + i++)})
    }

</script>

Now, this works, but only for the .chunk that is statically rendered on the page. When I press the button a second chunk appears, but that button does not work. If I add the html for two or more chunks to be rendered, each one works, but the buttons for the chunks it creates do not. What should I do?

+2  A: 

Use the "live" jQuery function.

$(".addChunk").live('click'. function(){create_chunk(this.parentNode)});

The problem is that you're binding to a single element. The "live" option will monitor the document for any clicks on elements that have the ".addChunk" class.

jvenema
.delegate() > .live()
jAndy
+1  A: 

replace

.bind()

with

.live()

or even better use

.delegate()

which is in your case:

$('#chunk-1').delegate('.addChunk', 'click', function(){create_chunk(this.parentNode);})

furthermore, go to www.jquery.com and read the documentation.

jAndy
+3  A: 

The event handler in the below line attaches the click event to the element matching the selector when you add the handler.

$(".addChunk").click(function(){create_chunk(this.parentNode)})

you can use the live handler to do this. the following code will solve your problem

$(".addChunk").live('click'. function(){create_chunk(this.parentNode)});
Elangovan
.delegate() > .live()
jAndy
@jAndy - The question says another chunk is added...so what would you delegate on? `#chunk-1` doesn't work here, you need a higher ancestor.
Nick Craver
Ohh well, for some reason I just assumed OP wants to duplicate an item within the div.
jAndy