admin管理员组文章数量:1296481
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.
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.
Share Improve this question edited May 24, 2015 at 19:25 anshabhi 4236 silver badges29 bronze badges asked May 24, 2015 at 18:37 JulyJuly 151 gold badge1 silver badge7 bronze badges 2-
1
Try
document.write(name);
– b2238488 Commented May 24, 2015 at 18:39 - Possible duplicate of This – anshabhi Commented May 25, 2015 at 4:50
4 Answers
Reset to default 1So you want to append some text to <body>
?
function smth(str) {
return document.body.appendChild(document.createTextNode(str));
}
This is making use of the following DOM Methods
node.appendChild
document.createTextNode
(ordocument.createElement
)
Please notice that it won't introduce formatting (such as line brakes <br />
), if you want those you'd need to add them too.
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.
<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>
One of the very mon ways to do this is using innerHTML
. Suppose you declare a <p>
in the <body>
as output, then you can write:
<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>
try using:
var yourvar='value';
document.body.innerHTML = yourvar;
本文标签: Display javascript variable in html bodyStack Overflow
版权声明:本文标题:Display javascript variable in html body - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741636295a2389658.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论