jquery remove() problem
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+'">&l开发者_如何学Pythont;/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!!!
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.
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')...
you can try $('#'+id).hide();
You need to use live()
Here is your updated jsFiddle
You need to use the live function for the second function
$('.btn').live('click',function(){
var id;
id = $(this).attr('alt');
$('#'+id).remove();
});
精彩评论