2016-05-18 25 views
0

我有一個htmlString。我將該字符串放入iframe中。 代碼是在插入DOM之前操縱html字符串

var iframe = document.createElement('iframe'); 
var html = '<html> <head></head> <body> //contents </body> </html>'; 

document.body.appendChild(iframe); 
iframe.contentWindow.document.open(); 
iframe.contentWindow.document.write(html); 
iframe.contentWindow.document.close(); 

現在我想要做的就是插入一個標籤

<base href="some url" > 

到htmlString的頭。然後我想將iframe附加到dom中並將htmlString寫入該iframe。

如何在插入iframe之前修改htmlString?

回答

1

在這裏你去:https://jsfiddle.net/tjcwyem6/

我用下面的JavaScript:

var iframe = document.createElement('iframe'), 
    html = '<html> <head></head> <body> //contents </body> </html>', 
    newurl = "https://www.facebook.com/", 
    basehref = "<base href='" + newurl + "'>", 
    n = html.indexOf("</head>"); 

var newhtml = [html.slice(0, n), basehref, html.slice(n)].join(''); 

document.body.appendChild(iframe); 
iframe.contentWindow.document.open(); 
iframe.contentWindow.document.write(newhtml); 
iframe.contentWindow.document.close(); 

console.log(newhtml); 

我的修改,請執行下列操作:在newurl

  1. 商店中的URL值。
  2. 把它放在一個字符串basehref
  3. 在您的HTML字符串中獲取</head>所在的位置。
  4. basehref添加到newhtml通過切片和連接字符串。
0

可以能夠使用jQuery像追加iframe中的內容 -

$("iframe").contents().find("head").append('<base href="some url" >'); 
+0

儘管這樣更乾淨,更自然,但在將字符串插入iframe之前不會操縱字符串。 –

0

您可以通過加載到jQuery的XML和使用jQuery來操縱操縱HTML:

var xml = $.parseXML("<html> <head></head> <body> //contents </body> </html>");  
$("head", xml).append("<base url='x'/>") 

var html; 
if (window.ActiveXObject) { 
    html = xml.xml; 
} else { 
    html = (new XMLSerializer()).serializeToString(xml); 
} 

iframe.contentWindow.document.write(html); 

This answer for xml to html的詳細信息

無法將html作爲html加載到jquery中,因爲它會去掉body/head。

0
String.prototype.insertAt=function(index, string) { 
     return this.substr(0, index) + string + this.substr(index); 
} 
var myhtml = "<html> <head></head> <body></body> </html>"; 
var m = myhtml.indexOf("</head>"); 
myhtml = myhtml.insertAt(m, '<base href="some url" >'); 
console.log(myhtml);