使用JQuery解析包含html的字符串
令人惊讶的是,这个问题没有出现在相关问题列表中。有一些类似的东西,但我想知道:使用JQuery解析包含html的字符串,jquery,html,Jquery,Html,令人惊讶的是,这个问题没有出现在相关问题列表中。有一些类似的东西,但我想知道: string s = "<p>Cats</p><div id='fishbiscuits'>myValue</div>"; string s=“CatsmyValue”; 我想使用JQuery来获取我的值 如何实现这一点?使用jQuery函数创建对象,然后您可以像使用任何其他元素集合一样使用它。其中任何一个都可以正常工作: // Using filter() $(s
string s = "<p>Cats</p><div id='fishbiscuits'>myValue</div>";
string s=“CatsmyValue”;
我想使用JQuery来获取我的值
如何实现这一点?使用jQuery函数创建对象,然后您可以像使用任何其他元素集合一样使用它。其中任何一个都可以正常工作:
// Using filter()
$(s).filter("#fishbiscuits").text();
// Wrapping with a div and using find()
$('<div>' + s + '</div>').find("#fishbiscuits").text();
// Wrapping with a div and using selector context
$('#fishbiscuits', '<div>' + s + '</div>').text();
// Creating a div, setting the html and then using find
$('<div>').html(s).find("#fishbiscuits").text();
//使用过滤器()
$(s).过滤器(“#鱼饼干”).text();
//用div换行并使用find()
$(“”+s+“”)。查找(“#鱼饼干”).text();
//使用div换行并使用选择器上下文
$('#鱼饼干',''+s+'').text();
//创建一个div,设置html,然后使用find
$(“”).html(s).find(“#鱼饼干”).text();
根据提供的信息,这应该可以做到:
var s = "<p>Cats</p><div id='fishbiscuits'>myValue</div>";
var dummyElement = $( '<div>' + s + '</div>' );
var yourString = $( '#fishbiscuits', dummyElement ).html ();
var s=“CatsmyValue”;
变量dummeyelement=$(''+s+'');
var yourString=$('#fishbickets',dummeyelement.html();
它基本上会创建一个新的DOM元素,其中包含字符串中的HTML,然后搜索id为“Fishcookies”的元素并返回其内部HTML,尽管由于
#fishcookies
位于该文档的“根”处,您需要.filter()
而不是.find()
,或者将s
包装在另一个元素中,如:$('+s+'')。查找(“#鱼饼干”).text()
@SLC:请参阅我的编辑,@gnarf:谢谢你的更正,当我最初阅读问题时,我认为它已经包装好了。另一个想法:$(''.html(s)。查找(“#鱼饼干”).text()代码>另一个想法:$(s).兄弟姐妹(“#鱼饼干”).text()代码>@All:添加了一系列选项:-)没有线索,固溶体。。。除了第三行中缺少的$
:)。。。另外,我个人认为dummeyelement.find(“#鱼饼干”)
比$(“#鱼饼干”,dummeyelement)
字符串s=
应该是var s=
…+1,只是为了让我们搜索鱼饼干
。。。。