Reputation: 4524
I'm having some issues with removing some HTML elements.
Just a few words about my code.
I'm cloning <ul>
and then showing its content using a popup dialog. Then in 2dim array where I'm saving the <li>
corresponding objects between the original and the cloned. So, removing from the cloned one and confirming gives results in the original <ul>
.
The problem I am experiencing is when adding jQuery animation and removing in its callback function probably because of the "for" loop. Then, when removing additionally for a second time without closing the dialog window, the bugs come out by removing elements improperly!
If you're not witnessing it from the first, try playing little bit more, it won't be long until you see it!
Here's the difference working without .hide animation : http://jsfiddle.net/TTGr7/1/
buggy with animation: http://jsfiddle.net/TTGr7/2/
The key part and the difference is in that section of the code:
del.click(function() {
var len = markedForDel.b.length;
if (len > 0) {
var confirmation = confirm('Delete marked groups');
if (confirmation) {
for (var i = 0; i < len; i++) {
markedForDel.a[i].remove();
markedForDel.b[i].remove();
//markedForDel.a.splice(i,1);
//markedForDel.b.splice(i,1);
}
}
}
});
and
del.click(function() {
var len = markedForDel.b.length;
if (len > 0) {
var confirmation = confirm('Delete marked groups');
if (confirmation) {
for (var i = 0; i < len; i++) {
markedForDel.a[i].hide(function(){
markedForDel.a[i].remove();
});
markedForDel.b[i].remove();
//markedForDel.a.splice(i,1);
//markedForDel.b.splice(i,1);
}
}
}
});
So I really need to keep the .hide animation and still remove groups properly.
So I'm really counting on your kind help, BR
Upvotes: 0
Views: 57
Reputation: 26633
If the for loop has incremented the value of i
by the time the hide callback is invoked, then you will pass the wrong element to remove. Try this, instead:
markedForDel.a[i].hide(function() {
$(this).remove();
});
Within the hide method's callback, this
is set to the element that was just hidden.
Upvotes: 3
Reputation: 76910
Have you tried
del.click(function() {
var len = markedForDel.b.length;
if (len > 0) {
var confirmation = confirm('Delete marked groups');
if (confirmation) {
for (var i = len -1; i >= 0; i--) {
markedForDel.a[i].hide(function(){
markedForDel.a[i].remove();
});
markedForDel.b[i].remove();
//markedForDel.a.splice(i,1);
//markedForDel.b.splice(i,1);
}
}
}
});
fiddlke here http://jsfiddle.net/TTGr7/3/
Upvotes: 0