简体   繁体   中英

How do I define a variable in my index.html file? (window.parentPage = true;)

https://stackoverflow.com/a/43635720

On this answer, it says to define a variable (window.parentPage = true;) in the index.html page. How can I go about doing this?

You would need to define the variable using JavaScript. You can embed some JavaScript in the HTML file by encasing it in a script tag like so:

<script type="text/javascript">
    window.parentPage = true;
</script>

First you need to clearly realize your reason... what you want to achieve.

After that defining that to yourself:

First option: You can store/save some data as stated on the link you added to your question inside a tag, like that:

<script>
    var myLittleBox = "box content";
</script>

And access it later like:

<script>
    myLittleBox = myLittleBox + " extra content";
    console.log(myLittleBox);
    //this will print "box content extra content"
</script>

You need to use the tag to access the javascript environment.

Second option: You can save/store data with pure HTML using an with type "hidden" to not show it on screen as an input box, and changing it's value, like that:

<input type="hidden" value="box content">

But this way you'll not be able to access the data directly without aid of javascript code, unless you send this input somewhere reachable as GET or POST within a and recover it getting the respective GET or POST.

Javascript variables:

https://www.w3schools.com/js/js_variables.asp

Ex:https://www.w3schools.com/js/tryit.asp?filename=tryjs_variables

HTML input:

https://www.w3schools.com/tags/tag_input.asp

HTML form handling:

https://www.w3schools.com/php/php_forms.asp

You're probably trying to understand the first option, but you question do not make that clear. Anyway, good studies.

Whatever you do you will have to use JavaScript in order to access the variable. An orthodox way of doing it that is not mentioned yet is using an data-attribute inside the html and than you access it by JavaScript:

 const attributeName = 'data-parentPage'; const setup = () => { let parentPageBool = document.querySelector(`html[${attributeName}]`).getAttribute(attributeName); console.log(parentPageBool) }; window.addEventListener('load', setup);
 <html data-parentPage="true"> </html>

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