【问题标题】:Convert HTML string to Jquery selector将 HTML 字符串转换为 Jquery 选择器
【发布时间】:2012-09-08 05:39:25
【问题描述】:

我有这样的 HTML 文本,它是使用 WinJS.xhr (Metro) 检索的。

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());

【问题讨论】:

  • 不知道你在这里问什么。 $("#getMe") 已经返回一个 jQuery 对象。这不是你想要做的吗?您可以将其分配给局部变量。 var $el = $("#getMe")
  • 我的意思是我有 HTML 字符串变量。如何从该字符串中获取#getMe,甚至更改#getMe 的文本。
  • 你的 HTML 字符串变量是什么?
  • >>> var myString = " ...

标签: jquery microsoft-metro


【解决方案1】:

根据您的最后一条评论,这是您要查找的内容。

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

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

【讨论】:

  • 我认为这是因为您在 html 字符串中包含了 html 和 body 标签。我测试了有和没有它,没有工作。如果是这种情况,您可以使用字符串操作从字符串中去除 标记。
【解决方案2】:

假设你的 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");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-24
    • 2014-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多