2012-09-15 73 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