使用jQuery过滤动态HTML

3

我正在尝试通过jquery创建一些动态的html,将它们过滤到我感兴趣的部分,并将该部分html添加到页面上现有的元素中,但它没有起作用。在这个fiddle里,我做错了什么?

http://jsfiddle.net/3zKeL/4/

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

如果你执行 console.log($(response)),你会看到只有 `[<h1>​hello​</h1>​],所以你可以使用 $(response).appendTo("#output");​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​`。 - Prasenjit Kumar Nag
2个回答

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


我在接受时太快了。过滤器返回的是所有内容(标题和head标签中的样式元素),而不仅仅是body标签中的内容:http://jsfiddle.net/dcwNJ/ - TugboatCaptain

0

好的,我解决了。当jQuery在动态生成的HTML中遇到“html”和“body”标签时,它会默默地抛出异常。我只需要替换或删除这些标签,现在它按预期工作。

http://jsfiddle.net/pqyeM/13/

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接