jQuery:append()和appendTo() [英] jQuery: append() vs appendTo()

查看:119
本文介绍了jQuery:append()和appendTo()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下代码测试jQuery的.append().appendTo()方法:

I am testing jQuery's .append() vs .appendTo() methods using following code:

$('div/>', {
    id : id,
    text : $(this).text()
    }).appendTo('div[type|="item"]#'+id);
$('div[type|="item"]#'+id).append($(this).text());

请注意,.appendTo().append()中的选择器相同,但后者起作用(在同一页面内),而前者不同.为什么?

Note that the selectors are identical in .appendTo() and .append(), yet the latter works (within the same page), while the former does not. Why?

如何让.appendTo()与这种类型的(复杂)选择器一起使用?两种方法的插值方式是否不同?我缺少一些语法吗?

How do I get .appendTo() to work with this type of (complex) selector? Do the two methods interpolate differently? Is there some syntax I'm missing?

我不想用无关紧要的代码弄乱帖子:足以说选择器引用的元素存在,正如.append()方法产生所需结果所证明的那样.让我知道是否需要更多信息.

I don't want to clutter the post with impertinent code: suffice it to say that elements referenced by selectors exist, as is evidenced by the .append() method producing desired result. Let me know if more info is needed.

谢谢!

推荐答案

要回答这个问题,您没有任何元素appendTo,因为您缺少字符(在本例中为 打开尖括号 <).

To answer the question, you don't have an element to appendTo anything, as you're missing characters (in your case it's an opening angle bracket <).

$('div/>',{});

需要成为

$('<div/>',{});

创建一个元素,否则它完全按照您说的去做-什么都没有!

to create an element, otherwise it does exactly what you say it does - nothing!

否则,您似乎顺序正确,就像这样:

Otherwise you seem to have the order of things right, it's like this:

  • .append() 将参数指定的内容插入到 匹配元素集中每个元素的结尾,如

  • .append() inserts the content specified by the parameter, to the end of each element in the set of matched elements, as in

$(Append_To_This).append(The_Content_Given_Here);

  • ,而 .appendTo() 可以其他方式解决 :插入每一个 匹配元素集中的元素到给定目标的末尾 在参数中,如

  • while .appendTo() works the other way around: it insert every element in the set of matched elements to the end of the target given in the parameter, as in

    $(The_Content_Given_Here).appendTo(Append_To_This);
    


  • 还有 .prepend()


    There's also .prepend() and prependTo() which works exactly the same, with the only difference being that the prepended elements are added at the beginning of the target elements content instead of the end.

    这篇关于jQuery:append()和appendTo()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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