而不是增加+1它将给出总数

时间:2017-02-12 10:19:25

标签: jquery ajax

如果我单击具有值'c'的按钮,它应该增加1,但不是递增1,而是给出了'c'的所有值的总和,因为我已经等于2两个'c'值。有人可以帮忙吗?

HTML

<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('.btn').click(function() {
  var value = $(this).attr("name", "one").val();
  var value2 = $(this).attr("name", "two").val();
  $.post("myFile.php", { one:value, two:value2 }, function(data){ 
  $('#divs') .html(data);
});
});
});
</script>

</head>
<body>
<div id="1">number one
<button class="btn" name="one" value="w">A</button>
<button class="btn" name="one" value="w">B</button>
<button class="btn" name="one" value="c">C</button>
<div id="divs"></div>
</div>
<div id="2">number two
<button class="btn" name="two" value="w">A</button>
<button class="btn" name="two" value="c">B</button>
<button class="btn" name="two" value="w">C</button>
<div id="divs"></div>
</div>
</body>
</html>

myFile.php

<?php
$count = 0;
$first= $_POST['one'];
$second= $_POST['two'];
if($first== 'c'){
    $count++;
}
if($second=='c'){
    $count++;
}
echo $count;
?>  

1 个答案:

答案 0 :(得分:0)

你需要这样的东西:

$(document).ready(function(){
    $('.btn').click(function() {
        var $this = $(this);
        var name = $this.attr('name');
        var thisValue = $this.val();
        var postData = {};
        ['one','two'].forEach(function(x) {
            data[x] = name == x ? thisValue : null;
        });
        $.post("myFile.php", postData, function(data){ 
            $('#divs').html(data);
        });
    });
});

P.S。但是我仍然无法理解你的方法为什么需要那个