在哪种情况下使用 .append() 更好,哪个 .appendTo()? [英] In which case it is better to use the .append(), and which .appendTo()?

查看:22
本文介绍了在哪种情况下使用 .append() 更好,哪个 .appendTo()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

除了语法之外,这些函数没有太大区别:

There is no big difference between those functions except the syntax:

$('.target').append('text');
$('text').appendTo('.target');

正如 jQuery docs 中所说:

.append() 和 .appendTo() 方法执行相同的任务.专业区别在于语法,特别是在内容和目标.使用 .append(),前面的选择器表达式该方法是插入内容的容器.和.appendTo(),另一方面,内容在方法之前,作为选择器表达式或动态创建的标记,以及它被插入到目标容器中.

The .append() and .appendTo() methods perform the same task. The major difference is in the syntax-specifically, in the placement of the content and target. With .append(), the selector expression preceding the method is the container into which the content is inserted. With .appendTo(), 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 into the target container.

那么在什么情况下最好使用.append(),哪个.appendTo()?哪些代码示例只适合这两个函数中的一个而另一个不够好?

So in which case it is better to use the .append(), and which .appendTo()? In which code-samples fit only one of those two functions and the other is not good enough?

同样的问题适用于:

  • .prepend() vs .prependTo()
  • .before() vs .insertBefore()
  • .after() vs .insertAfter().

推荐答案

你自己说的 --- 没有太大区别.但是,我对使用什么的选择通常取决于方法链,前提是您已经引用了元素.

You said it yourself --- there's not much difference. My choice of what to use, however, normally depends on method chaining, provided you already have your elements referenced.

var _target, _content;

_target.append(_content).addClass('foo');
// will add the foo class to _target

_content.appendTo(_target).addClass('foo');
// will add the foo class to _content

这篇关于在哪种情况下使用 .append() 更好,哪个 .appendTo()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆