假设我想从脚本标签内打印html.
像这样的来源
<div>foo</div>
<script>
print('<div>Print this after the script tag</div>');
</script>
<div>bar</div>
Run Code Online (Sandbox Code Playgroud)
在脚本运行后,应该在浏览器中看起来像这样
<div>foo</div>
<script>
print('<div>Print this after the script tag</div>');
</script>
<div>Print this after the script tag</div>
<div>bar</div>
Run Code Online (Sandbox Code Playgroud)
我可以为此目的编写我自己的代码但是因为这对我来说就像一个非常简单的问题,我猜我要么错过了某些东西,要么我的想法在某种程度上存在缺陷而且故意排除了打印.
另外,有点相关:我想知道脚本是否(或可以制作)知道它周围的脚本标签.通过这些信息,可以更容易地找到要注入的打印html代码的位置,假设它不是非常气馁.
澄清:我不需要你为我写一个打印功能.我只需要知道是否存在实现此目的的本机方法,我已经错过了它或者不应该这样做的原因.
编辑 我意识到我没有想到这个问题.
我直截了当地了解了事实,现在几乎所有事情似乎都在起作用.我应该最初提到模板内部需要打印功能 - 我正在进行模板引擎实验.我设法通过从简单的html中分离脚本并将分离的html sans脚本与脚本输出连接来解决这个问题.
当我编写代码时,我注意到由于js的异步性,一切都不会那么顺利.我想我希望能够在模板中做任何类型的js魔术,就像我在php中一样.似乎实际上在模板内部以傻瓜式方式支持异步代码需要更多的思考.
Mik*_*ant 60
你需要使用 document.write()
<div>foo</div>
<script>
document.write('<div>Print this after the script tag</div>');
</script>
<div>bar</div>
Run Code Online (Sandbox Code Playgroud)
请注意,这仅在您编写文档的过程中有效.文档渲染完成后,调用document.write()
将清除文档并开始编写新文档.如果这是您的使用案例,请参阅此问题提供的其他答案.
Lan*_*nce 31
你可以使用document.write,但这不是一个好习惯,它可能会清除整个页面取决于它何时被执行.
你可以Element.innerHtml
像这样使用:
<div>foo</div>
<span id="insertHere"></span>
<div>bar</div>
<script>
document.getElementById('insertHere').innerHTML = '<div>Print this after the script tag</div>';
</script>
Run Code Online (Sandbox Code Playgroud)
您可以使用
function echo(content) {
var e = document.createElement("p");
e.innerHTML = content;
document.currentScript.parentElement.replaceChild(document.currentScript, e);
}
Run Code Online (Sandbox Code Playgroud)
它将用内容参数中的文本替换当前正在执行的调用 echo 函数的脚本。
// usage: log('inside coolFunc',this,arguments);
// http://paulirish.com/2009/log-a-lightweight-wrapper-for-consolelog/
window.log = function(){
log.history = log.history || []; // store logs to an array for reference
log.history.push(arguments);
if(this.console){
console.log( Array.prototype.slice.call(arguments) );
}
};
Run Code Online (Sandbox Code Playgroud)
使用window.log将允许您执行与console.log相同的操作,但它会先检查您使用的浏览器是否能够使用console.log,以免因兼容性原因而出错(IE 6等) .)。