我想进行计算并添加按钮来存储第一个操作数和"+",然后删除所有数字,以便我可以输入第二个操作数。比输入第二个操作数。之后,单击按钮将第一个操作数,第二个操作数和"+"发送到php。
这是演示
我还没有完成PHP代码,它只是一个"测试"代码来提醒结果。
我的代码由于我不知道的原因而无法正常工作。
<?
php print_r($_POST);
?>
您需要对 js 代码进行一些编辑。
(1)在$(document).on('click', 'button.number', function () {
中,您需要检查当前值是否为.function
(运算符),如果是,请在将值设置为数字之前将运算符添加到memory
。我使用了$.inArray($show.val(),['+','-','x','/']) !== -1
来检查它是否在数组中。
(2) 将$("#add").click(function () {
更改为 $(document).on('click', 'button.function', function () {
允许您使用此代码的所有.function
(运算符)按钮,而不仅仅是+
。
(3) 您需要将当前值添加到 memory
中,然后再将memory
发布到 php。
(4)您需要将execute: $.show.val()
更改为execute: memory
$(function () {
var $show = $('#display');
var currentDisplay = "";
$show.val(0);
$(document).on('click', 'button.number', function () {
if ($show.val().length >= 8) {
$show.val("Error");
} else if ($show.val() == "Error") {
$show.val("0");
}
// (1) check if current value is a .function
else if ($.inArray($show.val(),['+','-','x','/']) !== -1) {
var addOp = $show.val();
if (addOp) memory.push(addOp);
$show.val($(this).val());
}
else {
$show.val(($show.val() == "0" ? "" : $show.val()) + $(this).val());
}
});
$("#clear").click(function () {
$show.val("0");
});
$("#ce").click(function () {
if ($show.val().length >= 2) {
$show.val($show.val().substring(0, $show.val().length - 1));
} else {
$("#ce").trigger("click");
}
});
var memory = [];
// (2) changed from $("#add").click(function () { so all functions are registered
$(document).on('click', 'button.function', function () {
var addnum = $show.val();
if (addnum) memory.push(addnum);
$show.val($(this).val());
});
$('#equ').click(function () {
// (3) add current value to memory
var addnum = $show.val();
memory.push(addnum);
// (4) change execute: $show.val() to execute: memory
$.post("calculation.php", {
execute: memory
}, function (data,status) {
$show.val(data);
var e = memory.join('');
memory = [];
});
});
});
然后,在calculation.php
中,您希望遍历数组并根据运算符进行加/减。
<?php
if(isset($_POST['execute']) && is_array($_POST['execute'])) {
$total = (int)$_POST['execute'][0];
for($i=1;$i<count($_POST['execute']);$i+=2){
switch($_POST['execute'][$i]){
case '+': $total += (int)$_POST['execute'][$i+1];break;
case '-': $total -= (int)$_POST['execute'][$i+1];break;
default : $total += (int)$_POST['execute'][$i+1];
}
}
echo $total;
}
else echo 'Error';
?>
(注意:我只在 php 中做了+
和-
,假设您可以弄清楚如何添加*
和/
)
这是一个更新的 jsFiddle - http://jsfiddle.net/9t78jd47/3/(它使用 js 代码,而不是 $.post()
来模拟向calculation.php
发送memory