[英]function variable not passing to global variable
大家好,我有两页php文件和一个外部javascript文件。 我想将选定的单选按钮的值传递给jquery全局变量,以便可以查看与选定的单选按钮的值具有相同ID的div元素。 每当我单击“ PLAY!
按钮我在下一页看不到我的div元素。 这是我的代码:
player-choose.php
脚本:
<head>
<script src="js/jquery-1.9.1.min.js"></script>
<script src="js/mycustom.js"></script>
</head>
<body>
<div id="player-list">
<input type="radio" name="player" value="fighter" id="fighter-radio"><label for="fighter-radio"><img src="images/heroes/fighter-01.png" width="74" height="70"></label>
<input type="radio" name="player" value="pakhi" id="pakhi-radio"><label for="pakhi-radio"><img src="images/heroes/pakhi.png" width="95" height="70"></label>
</div>
<button id="play">PLAY!</button>
</body>
mycustom.js
脚本:
var playerID;
function start(){
spawnhero();
}
$(function(){
$("#play").click(function(){
window.location.href = 'index.php';
playerID = $('input[name=player]:checked').val();
});
})
function spawnhero () {
$("#content").append($("<div>").attr('id', playerID));
}
index.php
脚本:
<head>
<script src="js/jquery-1.9.1.min.js"></script>
<script src="js/mycustom.js"></script>
</head>
<body onload="start()">
<div id="content">
<div id="galaxy"></div>
</div>
</body>
这很简单,但是我不知道为什么它不起作用。 我在这里做错什么了吗? 如果有人找到解决方案,请启迪。 天哪!
全局变量不是跨页面持久的。 加载index.php之后,它将具有新的全局范围(窗口变量)。
我建议传递一个参数。
$("#play").click(function(){
playerID = $('input[name=player]:checked').val();
window.location.href = 'index.php?id=' + playerID;
});
之后,在index.php脚本中,读取参数并进行相应分配。
如果您要移至新页面(window.location = ...),则需要一些稍微复杂的方式在这些页面之间传输信息-大多数情况下,HTTP / HTML是“无状态的”, Cookie之类的技术除外。 JavaScript变量被彻底清除-实际上是在每个新页面上重新解析整个JQuery库(并不是要避免这种情况)
对于视频游戏,只要玩家信息不包括服务器组件(我可能错了),我的建议就是将玩家信息保存在sessionStorage
。
https://developer.mozilla.org/zh-CN/docs/Web/Guide/API/DOM/Storage
但是,如果这是一个基于服务器的游戏,其中您选择的玩家对本地计算机不重要,那么您可能希望通过将页面请求的结构不同来将玩家ID发送到服务器:
window.location.href = 'index.php?playerId=' + playerId;
或通过POST
荷兰国际集团的数据作为一种形式; 最简单的方法是将提交按钮构造为<input type="submit">
,然后将所有<input>
元素包装在<form method="POST">
对象中。
https://developer.mozilla.org/zh-CN/docs/Web/HTML/Element/form
从那里,您的服务器软件可以根据给定的信息以不同的方式写出第二页的响应-您甚至可以使用PHP指令自定义在<script>
标记内编写的JavaScript。
var playerId = "<?php print($_POST['playerId']); ?>";
希望这可以帮助您入门。
替代解决方案是您可以使用JavaScript还是jQuery Cookie或localstorage。 您可以跨页面加载/重定向获取/设置值,但这些值不会传递到服务器。
var playerID = $('input[name=player]:checked').val();
$.cookie("playerId", playerID);
var playerID = $('input[name=player]:checked').val();
localStorage.setItem("playerId", playerID);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.