2012-09-15 41 views
1

我有这样的HTML文本,使用WinJS.xhr(Metro)检索。将HTML字符串转换为Jquery选择器

HTML

<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
<title>Untitled Document</title> 
<style> 
</style> 
</head> 
<body> 
<div id="getMe"> 
Something 
</div> 
</body> 
</html> 

我想将其转换为一个jQuery对象使用它的选择。例如:

$("#getMe").text("Something different"); 

@马克: 我试图用这个,但我不能让文本。

var yourString = "<html><body><div id=\"getMe\">TEST</div></body></html>"// somehow set to the above string 
$el = $(yourString).find("#getMe"); 
console.log($el.text()); 
+0

不知道你问这里。 $(“#getMe”)已经返回一个jQuery对象。这不是你想要做的吗?您可以将其分配给本地变量。 var $ el = $(“#getMe”) – Mark

+0

我的意思是我有HTML字符串变量。如何从该字符串获取#getMe,甚至更改#getMe的文本。 – Emerald214

+0

什么是您的HTML字符串变量? – Mark

回答

-1

假设你的HTML字符串是一个变量,那么你可以这样做:

var yourString = // somehow set to the above string 

var $html = $(yourString); 
$html.find("#getMe").text("Something different"); 

// and then to actually show it on the page: 
$html.appendTo("body"); 
// or to just add that "getMe" div to the page: 
$html.find("#getMe").appendTo("body"); 
+0

它不起作用... – Emerald214

0

这里是你在找什么根据您最后的评论。

var myString = "<html>...</html>", 
    $el = $(myString).find("#getMe"); // $el = the element you wanted. 

http://jsfiddle.net/SCY9b/1/

+0

请参阅我的编辑请 – Emerald214

+0

我认为它是因为您在html字符串中包含html和body标签。我测试了和没有它,没有工作。如果是这种情况,您可以使用字符串操作去除字符串中的标签。 – Mark