简体   繁体   中英

How do I change the value of a global variable from function?

What is the problem here when I click the buttons that are supposed to change the value?

 <html> <head> <script type="text/javascript"> var x = 45; var j = " I love pancakes"; </script> </head> <body> <button type="button" onclick="f1();">Click me to change number</button> <button type="button" onclick="f2();">Click me to change sentence</button> <center> <script type="text/javascript"> function f1() { if (x == 45) { x = 32; } } function f2() { if (j == " I like pancakes") { j = " I don't like pancakes"; } } document.write(x); document.write(j); </script> </center> </body> </html> 

You can change the value of these variables just the way you've done it. However, the document.write won't be re-run automatically. The text you see on the page won't change, even though the variables have been updated.

Try using DOM to modify the content of the page when your event handler runs.

 <html> <head> <script type="text/javascript"> var x = 45; var j = " I love pancakes"; </script> </head> <body> <button type="button" onclick="f1();">Click me to change number</button> <button type="button" onclick="f2();">Click me to change sentence</button> <center> <script type="text/javascript"> function update() { document.getElementById('output').innerHTML = x + j; } function f1() { if (x == 45) { x = 32; } update(); } function f2() { if (j == " I like pancakes") { j = " I don't like pancakes"; } update(); } document.write('<span id="output">'); document.write(x); document.write(j); document.write('</span>'); </script> </center> </body> </html> 

Try this:

 <html> <head> <script type="text/javascript"> var x = 45; var j = " I love pancakes"; </script> </head> <body> <button type="button" onclick="f1()">Click me to change number</button> <button type="button" onclick="f2()">Click me to change sentence</button> <p id="sentence"></p> <center> <script type="text/javascript"> document.getElementById("sentence").innerHTML=x+j; function f1(){ if (x == 45){ x = 32; } else { x = 45; } document.getElementById("sentence").innerHTML=x+j; } function f2(){ if (j == " I like pancakes"){ j = " I don't like pancakes"; } else { j = " I like pancakes"; } document.getElementById("sentence").innerHTML=x+j; } </script> </center> </body> </html> 

it uses the innerHTML property to change the content

There was also another problem: the write function were outside the function so it's never called

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