简体   繁体   English

全局更改javascript变量的值

[英]Changing value of a javascript variable globally

I have a page 1.php and the code goes here(just a clone) 我有一个页面1.php,代码在这里(只是一个克隆)

<?php
include '2.php'
?>
<script>
function rename(){
var x='renamedvalue';
}
</script>
<input type="button" onclick="return rename();">

And the page 2.php 和页面2.php

<script>
var x ='somevalue';
</script>

I have to change the value of this variable onclick button event on page1. 我必须在第1页上更改此变量onclick按钮事件的值。

Since you're including 2.php into 1.php, you'll end up having a single page. 由于将2.php包含在1.php中,因此最终将只有一个页面。 You could create a global Javascript value, like you already did in 2.php, like this: 您可以像在2.php中那样创建一个全局Javascript值,如下所示:

<script>
var x ='somevalue';
</script>

Your problem in 1.php lies here: 您在1.php中的问题就在这里:

var x='renamedvalue';

With this snippet, you are redefining a variable named x inside your rename function. 使用此代码段,您将在重命名函数中重新定义名为x的变量。 To use the global variable x, change the line above to exclude the "var" (which redeclares another local value "x" inside rename()): 要使用全局变量x,请更改上面的行以排除“ var”(它在rename()中重新声明另一个局部值“ x”):

x='renamedvalue';

If you want to pass variables between JS and PHP its probably easier to use forms: 如果要在JS和PHP之间传递变量,它可能更易于使用:

<script>
function rename(){
    var x='renamedvalue';
    document.getElementById("x").value = x;
}
</script>
<form action="2.php" method="post">
<input type="hidden" value="" id="x" name="x">
<input type="button" onclick="return rename();">
</form>

page2.php 使page2.php

<script>
var x ='<?php print $_POST["x"] ?>';
</script>

You will need to perform some input cleaning but you get the idea 您将需要执行一些输入清理操作,但是您知道了

defining variable outside the js function make it global and allow to change thee value on onclick event. 在js函数外部定义变量使其变为全局变量,并允许在onclick事件上更改它们的值。

<?php
include '2.php'
?>
<script>
var x = ''; //global variable
function rename(){
x='renamedvalue';
}
</script>
<input type="button" onclick="return rename();">

you must use the global variable x 您必须使用全局变量x

write x='renamedvalue' instead of var x='renamedvalue' x='renamedvalue'而不是var x='renamedvalue'

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

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