我正在尝试通过jquery创建一些动态html,将其过滤到我感兴趣的部分,并将html的那一部分附加到页面上的现有元素,但它不起作用。我在这个小提琴里做错了什么?
HTML:
<div id="output">This is the output:<br></div>
JQ:
var response = "<html><body><h1>hello</h1></body></html>";
$(response).filter("body").appendTo("#output");
答案 0 :(得分:3)
$(response)
.filter(function() {
return $("body");
})
.appendTo("#output");
你也可以
$('<div/>') // add response to fake div
.append(response)
.find('body') // find your target
.appendTo('#output'); // append the target
<强> DEMO 强>
答案 1 :(得分:0)
好的,想通了。当jQuery遇到动态生成的html中的“html”和“body”标签时,它会默默地呕吐。我只需要更换或剥离这些标签,现在它按预期工作。
var response = "<html><head><title>test</title><style>body{font-size:.9em;}</style></head><body bgcolor=\"white\"><h1>hello</h1></body></html>";
// we have to remove/replace certain tags or jquery will vomit with unexpected results
var modifiedResponse = response.replace("<html>", "").replace("</html>", "").replace("<body", "<div id='content'").replace("</body>", "</div>");
var wrappedSet = $(modifiedResponse);
wrappedSet.filter("div[id='content']").appendTo("#output");