jQuery wrap()仅适用于DOM,不适用于jQuery对象吗? [英] jQuery wrap() only works on the DOM, not on jQuery object?

查看:98
本文介绍了jQuery wrap()仅适用于DOM,不适用于jQuery对象吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在jQuery中使用javascript给出以下代码:

Given the following code in javascript with jQuery:

var inner = $('<p></p>')
var outer = inner.wrap('<div></div>')

console.log(inner.outerHTML())       // <p></p>
console.log(outer.outerHTML())       // <p></p>

我了解第一个输出. .wrap()返回原始对象以用于链接.

I understand the first output. .wrap() is returning the original object, for chaining purposes.

对于第二个输出,由于.wrap()函数应该修改/扩展inner变量,因此我希望<div><p></p></div>.

For the second output, I would expect <div><p></p></div> since the .wrap() function should modify/extend the inner variable.

.wrap()仅适用于DOM元素吗?不在新创建的jQuery对象上吗?

Does the .wrap() only works on DOM elements? Not on a newly created jQuery object?

在jQuery 2.1.1中使用Chorme

推荐答案

.wrap()也可用于不引用DOM中任何内容的jQuery对象,例如$('<p></p>').

.wrap() works also on jQuery objects that do not reference anything in the DOM, like $('<p></p>').

但是您必须正确询问结果.由于链接,您只能得到原始的jQuery对象,但是必须使用.parents()要求围绕它的新创建的元素才能获得预期的结果.

But you have to properly ask the result. Due to chaining, you only get the original jQuery object, but you have to ask for the newly created elements around it with .parents() to get your expected result.

$('<p></p>').wrap('<div></div>').parents()

将给出:<div><p></p></div>

笔记

很明显,我以前没有得到它,但是由于@ jfriend00的回答和评论,我开始理解它.另外我也怀疑jQuery对象是否只是对DOM中内容的引用,或者可能是全新的内容.

It's was obvious I was not getting it before, but due to the answer and comments from @jfriend00 I became to grasp it. Also I was in doubt if a jQuery object is only a reference to something in the DOM or could be something entirly new.

这篇关于jQuery wrap()仅适用于DOM,不适用于jQuery对象吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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