问题
When I add in a new <li>
into the list, and then I try to remove it, it won't let me remove newly added features from the list?
http://jsfiddle.net/43nWM/
Cheers
回答1:
Cause when the browser is reading your javascript code the dynamically added li isn't in the DOM, so it can't find it. Instead add the handler to the parent, and listen for the a like this:
$('#cblist').on('click', 'a', function(){
$(this).parent('li').remove();
return false;
});
Fiddle: http://jsfiddle.net/43nWM/3/
回答2:
You can try.
http://jsfiddle.net/43nWM/1/
$(function(){
$('#cblist a').live('click', function(){
$(this).parent('li').remove();
return false;
});
});
回答3:
You are binding the click event only to current 'remove' links, not future ones. Use event delegation for this, to cover both bases. Change:
$('#cblist a').click(function(){
to
$('#cblist').on('click', 'a', function() {
回答4:
The secret here is event delegation. When you call .click(function() {...})
or .on('click', function() {...})
that event handler is only assigned to elements that matched the selector when the code was run. It won't affect elements that are added later.
However, you can use event delegation to assign an event handler to a static element that will contain all of your dynamic elements, which will run the callback function whenever an element matching the dynamic selector triggers that type of event:
$('#cblist').on('click', 'a', function() {
$(this).parent('li').remove();
return false;
});
Take a look at the section titled Direct and delegated events in the documentation for the .on() function for more information.
回答5:
$(function(){
$('#cblist').on('click','a',function(){
$(this).parent('li').remove();
return false;
});
});
View this jsfiddle
回答6:
you should add this code to for addition on dynamic li
tags
$li = $('<li>'+name+'</li>');
$a = $('<a href="">remove</a>');
$a.click(function(){
$(this).parent('li').remove();
return false;
});
$li.append($a);
i have also updated the code on jsfiddle
回答7:
Another option is to use the on() function, as shown here: http://jsfiddle.net/43nWM/12/
To be honest, I actually prefer the other two solutions here though.
EDIT: Use on() instead. I originally proposed using live()
来源:https://stackoverflow.com/questions/11794624/jquery-cant-remove-li-once-added