我有threePHP文件。拳头是index.php
和第二是cal.php
和第三是search.php
。在cal.php
我在JavaScript设置两个变量。
<script>
$(document).ready(function () {
var startDate = "hi";
var endDate = "there";
console.log("Callback is being set!");
});
</script>
然后我包括此cal.php
和search.php
文件在我index.php
文件。
<div class="col-md-6 mt-20 pad-sm-0">
<?php
include("searchUI.php");
?>
</div>
<div class="col-md-6 mt-20 pad-sm-0 hidden-sm hidden-xs">
<?php
include("calendarUI.php");
?>
</div>
在index.php
一个按钮,点击我要访问cal.php
在search.php
文件中设置的变量。我尝试以下,但我在控制台中看到不确定的。
function performSearch() {
console.log(window.startDate);
console.log(window.endDate);
}
var
具有的功能范围,所以任何定义有只能在函数内部访问。
你可以声明不var
关键字,尽管它是在实践中高度皱起眉头它添加变量到全球范围。 (除非你用use strict;
运行会抛出一个错误)
$(document).ready(function () {
startDate = "hi"; // creates global variable, not recommended
endDate = "there";
console.log("Callback is being set!");
});
一个稍微像样的做法*将刚才设置的变量键在窗口对象类似于您试图访问它们的方式。
<script>
$(document).ready(function () {
window.startDate = "hi";
window.endDate = "there";
console.log("Callback is being set!");
});
</script>
改变你的脚本如下:
<script>
var startDate, endDate;;
$(document).ready(function () {
startDate = "hi";
endDate = "there";
console.log("Callback is being set!");
});
</script>
希望工程
您可以删除var关键字,这将使全球变量像下面。虽然有全局变量不是推荐的方法,因为有多个同名的全局变量可以有不良副作用。
全局变量被默认绑定到全局的window对象,所以你并不需要明确写入window.startDate。
<script>
$(document).ready(function () {
startDate = "hi";
endDate = "there";
console.log("Callback is being set!");
});
</script>