我有一個文本表示某個頁面。我需要將此文本轉換爲dom對象,提取body
元素並將其附加到我的dom中。將html頁面表示爲文本到dom對象
我用下面的代碼將文本轉換並提取body
元素:
$('body', $(text)).length
和:
$(text).filter('body').length
在返回0
這兩種情況下...
測試:http://jsfiddle.net/wEyvr/1/
我有一個文本表示某個頁面。我需要將此文本轉換爲dom對象,提取body
元素並將其附加到我的dom中。將html頁面表示爲文本到dom對象
我用下面的代碼將文本轉換並提取body
元素:
$('body', $(text)).length
和:
$(text).filter('body').length
在返回0
這兩種情況下...
測試:http://jsfiddle.net/wEyvr/1/
jQuery是p以非標準方式解析整個HTML,因此$(html)
無法按預期工作。
可以使用正則表達式和工作從那裏提取body標籤的內容:
// get the content of the body tags
var body = $(text.match(/<body[\s\S]*?>([\s\S]*?)<\/body>/i)[1]);
// append the content to our DOM
body.appendTo('body');
// bonus - to be able to fully use find -> we need to add single parent
var findBody = $("<body />").html(body.clone());
// now we are able to use selectors and have fun
findBody.find("div.cls").appendTo('body');
HERE是工作代碼。
編輯:更改代碼以顯示直接追加和也使用選擇器。
事情是這樣的:
var ifr = $("<iframe>"),
doc = ifr.appendTo("body")[0].contentWindow.document,
bodyLength;
doc.open();
doc.write(text);
doc.close();
bodyLength = ifr.contents().find("body").length;
ifr.remove();
alert(bodyLength);
你能不能把你的文字變成的jsfiddle?你的第一種方法看起來有效 – StuperUser 2011-12-13 17:15:08
第二種方法看起來像是使用find而不是filter來有效。 – kojiro 2011-12-13 17:17:37