在 html 正文中显示 javascript 变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30426969/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 05:10:16  来源:igfitidea点击:

Display javascript variable in html body

javascripthtml

提问by July

here is my approximate code:

这是我的大概代码:

 <script> 
function smth(){........}
    var name = smth('fullname');
 var hobby = smth('hobby');

    </script>

I need to display it normally in the html body. However, every way I tried gave me an alert window or it simply didn't work. I didn't find the similar solution. I know that the way above gives an alert windows as well, but I just wanted to show you the way I get my variables. Thanks in advance.

我需要在 html 正文中正常显示它。然而,我尝试的每一种方式都给了我一个警告窗口,或者它根本不起作用。我没有找到类似的解决方案。我知道上面的方法也提供了一个警告窗口,但我只是想向您展示我获取变量的方式。提前致谢。

回答by Paul S.

So you want to appendsome textto <body>?

所以,你要添加一些文字<body>

function smth(str) {
    return document.body.appendChild(document.createTextNode(str));
}

This is making use of the following DOM Methods

这是利用以下DOM 方法

Please notice that it won't introduce formatting (such as line brakes <br />), if you want those you'd need to add them too.

请注意,它不会引入格式(例如线刹车<br />),如果你想要那些你也需要添加它们。

回答by Tabaqui

With this approach you can target an element by ID and insert whatever you like inside it, but the solution suggested from Paul S is more simple and clean.

使用这种方法,您可以通过 ID 定位一个元素并在其中插入您喜欢的任何内容,但是 Paul S 建议的解决方案更简单明了。

<html>
    <head>
        <script type="text/javascript">
            var myVar = 42;
            function displayMyVar(targetElementId) {
                document.getElementById(targetElementId).innerHTML = myVar;
            }
        </script>
    </head>
    <body onload="displayMyVar('target');">
        <span id="target"></span>
    </body>
</html>

回答by anshabhi

One of the very common ways to do this is using innerHTML. Suppose you declare a <p>in the <body>as output, then you can write:

执行此操作的一种非常常见的方法是使用innerHTML. 假设你<p><body>as 输出中声明了一个,那么你可以这样写:

<script> function smth(){........}
var name=smth('fullname');
var hobby=smth('hobby')
var out=document.getElementById("output");
out.innerHTML=name; (or you may write hobby)
</script>

回答by Michal Bure?

try using:

尝试使用:

var yourvar='value';
document.body.innerHTML = yourvar;