Reputation: 6197
See HERE!!! http://jsfiddle.net/y5gbg/ When I type something, it should append a round div and text. When I click this round div, it should be removed. This is jquery code:
$(document).ready(function(){
$("button").click(function(){
var str;
str = $('input').val();
var sth;
sth = '<div id="'+str+'"><div class="btn" alt="'+str+'"></div><p>'+str+'</p><hr></div>';
$("#contents").append(sth);
});
$('.btn').click(function(){
var id;
id = $(this).attr('alt');
$('#'+id).remove();
});
});
But it doesn't work. Could someone tell me why? Another thing, how to do linebreak here? Thanks!!!
Upvotes: 0
Views: 615
Reputation: 6598
If you only need the button removed then your code would be:
$('.btn').live("click", function(){
$(this).remove();
});
instead of what you currently have for $('.btn')...
Upvotes: 1
Reputation: 7991
You need to use the live function for the second function
$('.btn').live('click',function(){
var id;
id = $(this).attr('alt');
$('#'+id).remove();
});
Upvotes: 0
Reputation: 25513
you just need to use the live function
$('.btn').live('click', function(){
var id;
id = $(this).attr('alt');
$('#'+id).remove();
});
because you're adding the div to the dom dynamically so the click isn't getting registered to the div
Here's an example of it working.
Upvotes: 4