简体   繁体   中英

HTML5/Javascript Adding Values From Head to Body

I need to be able to add variables declared in the script from the head of my code to the body of my code. More specifically need to be able to get the information that the user typed into the script and put that in place of something that would go in the body. Here is some code of what I am trying to explain:

<head>
<script>
var x="Type something here";
</script>
</head>
<body>
<p>I do love "var x"</p>
</body>

Essentially what I'm looking to do is take my variable x and put it into the body of the paragraph. The problem I'm running into is that I don't know how to add something to the body of the html without adding in the the quotes outside of something like var x or put part of a what I want in the paragraph and then add "var x" with a "+" sign without adding the "+" to the body of the paragraph. I know this is an easy thing but I suck at it and I've spent about 6 hours trying to figure this out. I appreciate the replies ahead of time. Thank you!

<html>
    <head>
        <script>
            var x="Type something here";
        </script>
    </head>
    <body>
        <p id="the_spot"></p>
        <script>
           document.getElementById( 'the_spot' ).innerHTML = "I do love " + x;
        </script>
    </body>
</html>

what i did above is use a javascript function innerHTML . this function changes the content of any element you specify. however, this function completely erases the existing contents of that element and re-write the contents you specified, in this case, "I do love Type something here". if you do not wish your existing contents to get erased, use append or prepend functions.

Happy coding :)

Input:

<head>
<script>
var x="Type something here";
</script>
</head>
<body>
<p id="var_x_modify">I do love "var x"</p>
</body>

javascript:

document.getElementById('var_x_modify').innerHTML=document.getElementById('var_x_modify').innerHTML.replace(/"var x"/,x);

You'll need a script to do that.

<p id="var-x">I do love "var x"</p>
<script type="text/javascript">
document.getElementById('var-x').innerHTML = "I do love " + x;
</script>

I also added an ID to the <p> to make it easier to find.

Try this one.

<head>
<script>
var x="Type something here";
window.onLoad = function(){
   var el= document.querySelector("#idx");
   el.innerHTML= x;
};
</script>
</head>
<body>
<p>I do love <span id="idx"></span></p>
</body>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM