我在页面上有一些图像,当点击其中一个图像时,POST数据被发送,页面刷新并且Javascript变量增加。我的问题是如何获得JS变量不重置为我重新加载页面时启动它的值?我之前也曾尝试使用localstorage
保存变量,但该变量仍然重置 - 这是合乎逻辑的,因为我在同一文档中进行了初始化,但我不知道该如何做。如何避免在页面刷新时重置Javascript变量?
我是Javascript新手,希望尽可能简单(如果可能,请获得一个虚拟答复)。
下面是我的代码,用相应的JavaScript在身体的开始(也有单独的文件中一些无关痛痒的PHP):
<?php
$subtest_nr = "7";
$counter = 0;
require_once('php.php');
?>
<!DOCTYPE html>
<html>
<head>
<title>Title</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<link rel="stylesheet" href="styles.css">
<script src="jquery-3.1.1.min.js"></script>
<script src="scripts.js"></script>
</head>
<body>
<script>
var counter = 0;
$(document).ready(function(){
$("img").click(function(){
counter += 4;
$("#test").text(counter); //for testing
});
$("#test").text(counter); //for testing
});
jQuery(function($) {
// Hide/suppress the submit button
$('input[type="submit"]').closest('div').hide();
// Bind to change event for all radio buttons
$('input[type="radio"]').on('change', function() {
// Submit the form ("this" refers to the radio button)
$(this).closest('form').submit();
});
});
</script>
<div class="main">
<div id="test"></div>
<?php $data = getData($subtest_nr); ?>
<form id="myform" method="post">
<div class="four_images">
<div class="flex-item">
<input type="radio" name="image" value="7.11" id="alt1" class="hidden">
<label for="alt1"><img src="images/<?php echo $data[$counter+0]; ?>"></label>
</div>
<div class="flex-item">
<input type="radio" name="image" value="7.12" id="alt2" class="hidden">
<label for="alt2"><img src="images/<?php echo $data[$counter + 1]; ?>"></label>
</div>
<div class="flex-item">
<input type="radio" name="image" value="7.13" id="alt3" class="hidden">
<label for="alt3"><img src="images/<?php echo $data[$counter+2]; ?>"></label>
</div>
<div class="flex-item">
<input type="radio" name="image" value="7.14" id="alt4" class="hidden">
<label for="alt4"><img src="images/<?php echo $data[$counter+3]; ?>"></label>
</div>
<div>
<input type="submit" name="save" value="Save Image Selection">
</div>
</div>
</form>
</div>
</body>
</html>
我可以补充一点,我想保持页面刷新因为后来我想将递增的变量传递给php,而不必使用Ajax或类似的方式发布它。 (希望这会让初学者更简单。)
您需要使用localStorage的持有价值,当页面初始化或者甚至更好,你读它,有PHP持有的价值,并将其写入到页面 – epascarello
您使用'localStorage'在正确的轨道上,所有你需要做的就是检查它在初始化之前是否存在它的起始值,所以它不会被重置。您也可以在PHP中使用会话。 –
@SpencerWieczorek啊,当然!谢谢!会试试这个。 – Ingrid