I understand that $fn.insertAfter() is used to insert element after the element supplied as the argument. How's $fn.after() different from it?

有帮助吗?

解决方案

$.fn.after()help inserts an element after the target element, on which you call it.

$('div').after('<div>new div</div>');

whereas, $.fn.insertAfter inserts the target element after the node you specify:

$('<div>new div</div>').insertAfter($('#someid'));

The latter is mostly prefered, because you keep a reference to the newly created element and can chain more methods on it. So for instance:

$('<div>new div</div>')
   .insertAfter($('#someid'))
   .attr('foo', 'bar')
   .css({
      'background-color': 'red'
   });

is possible. You cannot do that with .after()help. The same thing is for .append()help / .appendTo()help and .insertBefore()help / .before()help

其他提示

This is an example of the same thing, the difference is the context of the selector. insertAfter inserts the selected element after the parameter after inserts the parameter after the selected element.

$('<div id="foo"></div>').insertAfter('#bar');
$('#bar').after('<div id="foo"></div>');

Quoting straight from the documentation:

The .after() and .insertAfter() methods perform the same task. The major difference is in the syntax—specifically, in the placement of the content and target. With .after(), the selector expression preceding the method is the container after which the content is inserted. With .insertAfter(), on the other hand, the content precedes the method, either as a selector expression or as markup created on the fly, and it is inserted after the target container.

This mentions that they perform the same task but have different syntax.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top