简体   繁体   English

如何从函数更改全局变量的值?

[英]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. 但是, document.write不会自动重新运行。 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. 运行事件处理程序时,请尝试使用DOM来修改页面的内容。

 <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 它使用innerHTML属性更改内容

There was also another problem: the write function were outside the function so it's never called 还有另一个问题:write函数在函数之外,因此从不调用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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