简体   繁体   中英

jquery .after deleting entire li or table element

I'm seeing a problem using jquery .after to insert a div into an li. Essentially, the action is deleting the entire li...and I'm not sure why. I also saw this kind of problem using .after on different table elements which makes more sense to me because I can see that would break a table.

Take a look at this jsfiddle: http://jsfiddle.net/XrUtq/

The reason I have to do it this way is because I have to come up with a generic way to be able to put a div as CLOSE in the dom as possible to another element which I don't have control over (could be any kind of element). The div will then be relatively/absolutely positioned on the page to go over top the element which it is going after. I'm doing this because we need a solution instead of appending the div to the body, because if the view is changed then that appended element will stay on the page instead of dissapearing with the content which it is supposed to.

I hope I have made the problem clear enough. I've tried approaches like this:

if (nodeName === 'td' || nodeName === 'tr' || nodeName === 'th' || nodeName === 'tbody'){           
    popover.appendTo(editable.closest(':visible:not(tr):not(td):not(table):not(tbody)'));
}
else if(editable.is(':visible')){
    popover.after(editable);
}
else{
    $('body').append(popover);
}

but this is not accounting for the current problem with li.

Thanks for help/suggestions!

You're using slightly incorrect syntax (sort of backwards), use this instead:

Change this:

$('<div>Blabablabla</div>').after($('.editable'));

To this:

$('.editable').after('<div>Blabablabla</div>');

Working fixed example

jQuery .after(CONTENT) inserts the supplied content after the element you have selected. The after method should be appended to your jQuery selector. In your code you were placing the selector inside the after method.

I think you were intending to use .insertAfter() which would have worked with your original syntax.

http://jsfiddle.net/XrUtq/1/

$('li').click(function(){
    $('.editable').after('<div>Blabablabla</div>');
});

jQuery .after() inserts a target element (the div) after each element in the matched set (the .editable items). The syntax you were using is for jQuery .insertAfter() , an alternative method for doing a similar thing.

$('li').click(function(){
    $('<div>Blabablabla</div>').insertAfter('.editable');
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM