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
Add a ment  | 

4 Answers 4

Reset to default 1

So 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 (or document.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