有没有办法使用jQuery从变量查询HTML / XML内容? [英] Is there a way to query HTML/XML content from a variable using jQuery?

查看:208
本文介绍了有没有办法使用jQuery从变量查询HTML / XML内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在变量中有HTML内容,如下所示:

If I have HTML content in a variable like so:

var data = "<div id='myid'><div id='subid'>Text</div></div>";

有没有办法使用jQuery和selectors查询?
如果是HTML DOM:

Is there a way to query this using jQuery and selectors? As this, if it were HTML DOM:

var data = $("#myid > #subid").text();


推荐答案

使用jQuery的上下文

$doc = $("<div id='myid'><div id='subid'>Text</div></div>");
var data = $("#subid", $doc).text();

您的示例是错误的,因为它试图通过类(.subid)访问元素而不是通过id(#subid) - 也,如果你有一个元素的ID,没有必要像#myid> #subid一样,因为每个文档只有一个ID(如果你在做事情正确,至少)然后jQuery可以只做原生的document.getElementById()来查找元素。我测试了上面的,它工作正常。

Your example is wrong in that it is trying to access the elements by class (".subid") instead of by id ("#subid") - also, if you have an element's ID, it is not necessary to do something like "#myid > #subid" as since there is only one ID per document (if you're doing things properly, at least) then jQuery can just do the native document.getElementById() to find the element. I tested the above and it works fine.

这篇关于有没有办法使用jQuery从变量查询HTML / XML内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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