在javascript中是否有php echo / print等效物

时间:2022-05-02 22:26:51

Say I want to print html from inside a script tag.

说我想从脚本标签内打印html。

A source like this

像这样的来源

<div>foo</div>
<script>
print('<div>Print this after the script tag</div>');
</script>
<div>bar</div>

should look something like this in browser after the script has run

在脚本运行后,应该在浏览器中看起来像这样

<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>

I could write my own code for this purpose but since this looks to me like a very simple problem, I'm guessing either I've missed something or my thinking is flawed in some way and printing is left out intentionally.

我可以为此目的编写我自己的代码但是因为这对我来说就像一个非常简单的问题,我猜我要么错过了某些东西,要么我的想法在某种程度上存在缺陷而且故意排除了打印。

Also, somewhat related: I'd like to know if a script is (or can be made) aware of the script tags surrounding it. With this information it would be much easier to find the position for the printed html code to be injected into, assuming it's not highly discouraged.

另外,有点相关:我想知道脚本是否(或可以制作)知道它周围的脚本标签。通过这些信息,可以更容易地找到要注入的打印html代码的位置,假设它不是非常气馁。

To clarify: I don't need you to write a print function for me. I only need to know if a native method to achieve this exists and I've missed it or alternatively the reason it shouldn't be done.

澄清一下:我不需要你为我写一个打印功能。我只需要知道是否存在实现此目的的本机方法,我错过了它或者不应该这样做的原因。

EDIT I realized that I didn't think the question through.

编辑我意识到我没有想到这个问题。

I got my facts straight and now almost everything seems to be working. I should've originally mentioned that the print function was needed inside templates - I'm working on a template engine experiment. I managed to work it out by separating scripts from plain html and concatenating the split html sans scripts with script output.

我直截了当地了解了事实,现在几乎所有事情似乎都在起作用。我应该最初提到模板内部需要打印功能 - 我正在进行模板引擎实验。我设法通过从简单的html中分离脚本并将分离的html sans脚本与脚本输出连接起来来解决这个问题。

As I was writing the code I noticed that everything wouldn't go so smooth because of the asynchronous nature of js. I guess I was expecting to be able to do any kind of js magic in templates, just like I could in php. Seems like actually supporting async code in a fool-proof manner inside templates will require some more thought.

当我编写代码时,我注意到由于js的异步性,一切都不会那么顺利。我想我希望能够在模板中做任何类型的js魔术,就像我在php中一样。似乎实际上在模板内部以傻瓜式方式支持异步代码需要更多的思考。

9 个解决方案

#1


53  

You need to use document.write()

你需要使用document.write()

<div>foo</div>
<script>
document.write('<div>Print this after the script tag</div>');
</script>
<div>bar</div>

Note that this will only work if you are in the process of writing the document. Once the document has been rendered, calling document.write() will clear the document and start writing a new one. Please refer to other answers provided to this question if this is your use case.

请注意,这仅在您编写文档的过程中有效。文档渲染完成后,调用document.write()将清除文档并开始编写新文档。如果这是您的使用案例,请参阅此问题提供的其他答案。

#2


29  

You can use document.write, however it's not a good practice, it may clear the entire page depends on when it's being executed.

您可以使用document.write,但这不是一个好习惯,它可能会清除整个页面取决于它何时被执行。

You can use Element.innerHtml like this:

您可以像这样使用Element.innerHtml:

<div>foo</div>
<span id="insertHere"></span>
<div>bar</div>

<script>
var el = document.getElementById('insertHere');
el.innerHTML = '<div>Print this after the script tag</div>';
</script>

#3


3  

// 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) );
  }
};

Using window.log will allow you to perform the same action as console.log, but it checks if the browser you are using has the ability to use console.log first, so as not to error out for compatibility reasons (IE 6, etc.).

使用window.log将允许您执行与console.log相同的操作,但它会检查您使用的浏览器是否能够首先使用console.log,以免出于兼容性原因而出错(IE 6等) )。

#4


2  

You can use

您可以使用

function echo(content) {  
    var e = document.createElement("p");
    e.innerHTML = content;
    document.currentScript.parentElement.replaceChild(document.currentScript, e);
}

which will replace the currently executing script who called the echo function with the text in the content argument.

这将取代当前正在执行的脚本,该脚本使用content参数中的文本调用echo函数。

#5


1  

From w3school's page on JavaScript output,

从w3school的JavaScript输出页面,

JavaScript can "display" data in different ways:

JavaScript可以以不同的方式“显示”数据:

Writing into an alert box, using window.alert().

使用window.alert()写入警告框。

Writing into the HTML output using document.write().

使用document.write()写入HTML输出。

Writing into an HTML element, using innerHTML.

使用innerHTML写入HTML元素。

Writing into the browser console, using console.log().

使用console.log()写入浏览器控制台。

#6


0  

You can use document.write or even console.write (this is good for debugging).

您可以使用document.write甚至console.write(这对调试很有用)。

But your best bet and it gives you more control is to use DOM to update the page.

但是你最好的选择是让你更多的控制是使用DOM来更新页面。

#7


0  

$('element').html('<h1>TEXT TO INSERT</h1>');

or

要么

$('element').text('TEXT TO INSERT');

#8


0  

this is an another way:

这是另一种方式:

<html>
<head>
    <title>Echo</title>
    <style type="text/css">
    #result{
        border: 1px solid #000000;
        min-height: 250px;
        max-height: 100%;
        padding: 5px;
        font-family: sans-serif;
        font-size: 12px;
    }
    </style>
    <script type="text/javascript" lang="ja">
    function start(){
        function echo(text){
            lastResultAreaText = document.getElementById('result').innerHTML;
            resultArea = document.getElementById('result');
            if(lastResultAreaText==""){
                resultArea.innerHTML=text;
            }
            else{
                resultArea.innerHTML=lastResultAreaText+"</br>"+text;
            }
        }

        echo("Hello World!");
        }
    </script>
</head>
<body onload="start()">
<pre id="result"></pre> 
</body>

#9


0  

l('output text example')

after once defining

经过一次定义

l=console.log

seems fine to me for a quick hacksy JS debugging in the browser console.

对于我来说,在浏览器控制台中快速进行hacksy JS调试似乎很好。

Based on @Lil' Bits’s answer – thanks!

根据@Lil'Bits的回答 - 谢谢!

#1


53  

You need to use document.write()

你需要使用document.write()

<div>foo</div>
<script>
document.write('<div>Print this after the script tag</div>');
</script>
<div>bar</div>

Note that this will only work if you are in the process of writing the document. Once the document has been rendered, calling document.write() will clear the document and start writing a new one. Please refer to other answers provided to this question if this is your use case.

请注意,这仅在您编写文档的过程中有效。文档渲染完成后,调用document.write()将清除文档并开始编写新文档。如果这是您的使用案例,请参阅此问题提供的其他答案。

#2


29  

You can use document.write, however it's not a good practice, it may clear the entire page depends on when it's being executed.

您可以使用document.write,但这不是一个好习惯,它可能会清除整个页面取决于它何时被执行。

You can use Element.innerHtml like this:

您可以像这样使用Element.innerHtml:

<div>foo</div>
<span id="insertHere"></span>
<div>bar</div>

<script>
var el = document.getElementById('insertHere');
el.innerHTML = '<div>Print this after the script tag</div>';
</script>

#3


3  

// 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) );
  }
};

Using window.log will allow you to perform the same action as console.log, but it checks if the browser you are using has the ability to use console.log first, so as not to error out for compatibility reasons (IE 6, etc.).

使用window.log将允许您执行与console.log相同的操作,但它会检查您使用的浏览器是否能够首先使用console.log,以免出于兼容性原因而出错(IE 6等) )。

#4


2  

You can use

您可以使用

function echo(content) {  
    var e = document.createElement("p");
    e.innerHTML = content;
    document.currentScript.parentElement.replaceChild(document.currentScript, e);
}

which will replace the currently executing script who called the echo function with the text in the content argument.

这将取代当前正在执行的脚本,该脚本使用content参数中的文本调用echo函数。

#5


1  

From w3school's page on JavaScript output,

从w3school的JavaScript输出页面,

JavaScript can "display" data in different ways:

JavaScript可以以不同的方式“显示”数据:

Writing into an alert box, using window.alert().

使用window.alert()写入警告框。

Writing into the HTML output using document.write().

使用document.write()写入HTML输出。

Writing into an HTML element, using innerHTML.

使用innerHTML写入HTML元素。

Writing into the browser console, using console.log().

使用console.log()写入浏览器控制台。

#6


0  

You can use document.write or even console.write (this is good for debugging).

您可以使用document.write甚至console.write(这对调试很有用)。

But your best bet and it gives you more control is to use DOM to update the page.

但是你最好的选择是让你更多的控制是使用DOM来更新页面。

#7


0  

$('element').html('<h1>TEXT TO INSERT</h1>');

or

要么

$('element').text('TEXT TO INSERT');

#8


0  

this is an another way:

这是另一种方式:

<html>
<head>
    <title>Echo</title>
    <style type="text/css">
    #result{
        border: 1px solid #000000;
        min-height: 250px;
        max-height: 100%;
        padding: 5px;
        font-family: sans-serif;
        font-size: 12px;
    }
    </style>
    <script type="text/javascript" lang="ja">
    function start(){
        function echo(text){
            lastResultAreaText = document.getElementById('result').innerHTML;
            resultArea = document.getElementById('result');
            if(lastResultAreaText==""){
                resultArea.innerHTML=text;
            }
            else{
                resultArea.innerHTML=lastResultAreaText+"</br>"+text;
            }
        }

        echo("Hello World!");
        }
    </script>
</head>
<body onload="start()">
<pre id="result"></pre> 
</body>

#9


0  

l('output text example')

after once defining

经过一次定义

l=console.log

seems fine to me for a quick hacksy JS debugging in the browser console.

对于我来说,在浏览器控制台中快速进行hacksy JS调试似乎很好。

Based on @Lil' Bits’s answer – thanks!

根据@Lil'Bits的回答 - 谢谢!