我可以在未附加到DOM的HTML字符串上使用jQuery选择器吗? [英] Can I use jQuery selectors on an HTML string that is not attached to the DOM?

查看:50
本文介绍了我可以在未附加到DOM的HTML字符串上使用jQuery选择器吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,如果我有一个变量,如

So if I have a variable like

var ht = "<body><p>Paragraph Here</p></body>"

如果将其附加到DOM上,我可以这样做以获取文本

If it was attached to the DOM I could just do this to get the text

$('p').text(); 

但是我可以只对尚未附加到变量上的变量进行相同选择吗?

But can I do the same kind of selection just on a variable that has not yet been attached to the dom?

推荐答案

jQuery对象将采用HTML并将其放入DOM结构中以进行进一步查询,您可以将其传递给直接创建对象,或者如果您只想查询它,则将其用作上下文。

The jQuery object will take HTML and make it in to a DOM structure for further query, you can pass it in directly to create the object, or use it as a context if you just wish to query it.

编辑:由于某种原因,似乎有必要将其包装DIV(如果在此示例中还不包含在内)。有关更多信息,请参见 jQuery对象文档

请参阅系统测试框架,网址为: http:/ /jsfiddle.net/hUMqU/

var ht = "<body><p>Paragraph Here</p></body>";
$('<div>' + ht + '</div>').find('p').text();

或作为上下文:

var ht = "<body><p>Paragraph Here</p></body>";
$('p', '<div>' + ht + '</div>').text();

这篇关于我可以在未附加到DOM的HTML字符串上使用jQuery选择器吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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