[英]Manipulate html String before inserting into DOM
我有一个htmlString。 然后,我将该字符串放入iframe。 该代码是
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。
如何在将htmlString插入iframe之前对其进行操作?
在这里,您可以前往: 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
。 basehref
。 </head>
位置。 basehref
到newhtml
通过切割和连接字符串。 您可以使用jquery附加iframe内容,例如-
$("iframe").contents().find("head").append('<base href="some url" >');
您可以通过将html作为XML加载到jquery中并使用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);
xml到html的详细答案
您无法将html作为html加载到jquery中,因为它会剥离正文/头部。
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.