减去变量PHP

时间:2014-04-09 20:10:10

标签: php html

我无法弄清楚每次点击html链接时如何从变量($ energia)中减去2。问题是它只减去一次,所以输出总是18。

<?php 
$energia = 20;


if(isset($_GET["action"]) && $energia != 0)
{
$energia -=2;

}
}
?>


<a href="?action" >subtract</a> <?php echo $energia2; ?>

2 个答案:

答案 0 :(得分:3)

这能否为您提供所需的结果?

<?php
//checks if num is set, if not, set it to 20 by default
/*
The following line is the same as
if(isset($_GET["num"]))
{
    $energia = $_GET["num"];
}
else
{
    $energia = 20;
}
*/
//value       condition             if true     else
$energia = isset($_GET["num"]) ? $_GET["num"] : 20;

//if action was clicked and energia is not 0 (not to go in negatives)
//remove && $energia != 0 to allow negative numbers
if(isset($_GET["action"]) && $energia != 0)
{
    //substract 2 from energia
    $energia -=2;
}
?>

此行将action设置为true并且还将energia的值存储在substact链接字符串中。单击时,将使用$ _GET [&#34; num&#34;]检索它。在链接之后,向用户显示当前值(与链接中相同)。

<a href="?action=true&amp;num=<?php echo $energia; ?>" >subtract</a> <?php echo $energia; ?>

答案 1 :(得分:2)

这是一个jquery解决方案:jsfiddle

HTML

<span class="energia"></span>
<br/>
<a href="#" class="subtract">subtract</a>

jquery的

var energia = 20;
$('.energia').text(energia);
$(document).on('click','.subtract', function(){
       energia -= 2;
       $('.energia').text(energia);
        return false;
});