根据点击位置

时间:2017-08-15 20:38:22

标签: javascript jquery

我希望变量根据我点击的位置递增。然后能够减少点击的位置。然而第一个增量没有存储在z中,因此当我进行第二个增量时它不会添加第一个增量,只需发布​​第二个增量。我怎样才能使这个增量工作?这是代码:

$(".pesqopcao").click(function() {
  var color = $(this).css("background-color");
  var z = 0;
  if (color == 'rgb(255, 255, 255)' || color == 'white') {
    $(this).css("background-color", "blue");
    z += (this.id * 1);
    document.getElementById("z").innerHTML = z;
  } else
  if (color == 'rgb(0, 0, 255)' || color == 'blue') {
    $(this).css("background-color", "white");
    z - (this.id * 1);
    document.getElementById("z").innerHTML = z;
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="101" class="pesqopcao">101</div>
<div id="601" class="pesqopcao">601</div>
<div id="901" class="pesqopcao">901</div>

<div id="z"></div>

2 个答案:

答案 0 :(得分:1)

您需要在jQuery click事件之外声明您的变量,以使其在点击之间保持不变。

此外,第11行上的拼写错误:您正在从z中减去但不将其设置为任何内容。应该是z -=而不是z -

var z = 0;

$(".pesqopcao").click(function() {
  var color = $(this).css("background-color");
  if (color == 'rgb(255, 255, 255)' || color == 'white') {
    $(this).css("background-color", "blue");
    z += (this.id * 1);
    document.getElementById("z").innerHTML = z;
  } else if (color == 'rgb(0, 0, 255)' || color == 'blue') {
    $(this).css("background-color", "white");
    z -= (this.id * 1);
    document.getElementById("z").innerHTML = z;
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="101" class="pesqopcao">101</div>
<div id="601" class="pesqopcao">601</div>
<div id="901" class="pesqopcao">901</div>

<div id="z"></div>

答案 1 :(得分:0)

1-value of z as it is an id so string parseInt it.

2声明变量作为全局(无var关键字)外部函数。 3- $(this).id未定义使用jquery api的attr方法

&#13;
&#13;
$(document).ready(function(){
 z=0;
$(".pesqopcao").on('click',function() {
var color = $(this).css("background-color");
if (color == 'rgb(255, 255, 255)' || color == 'white') {
  $(this).css("background-color", "blue");
  z+=parseInt($(this).attr('id'));
  document.getElementById("z").innerHTML = z;
}else{
if (color == 'rgb(0, 0, 255)' || color == 'blue') {
  $(this).css("background-color", "white");
  z-=parseInt($(this).attr('id'));
  $("#z").text(z);
}
}
});
});
&#13;
.pesqopcao{background-color:white;}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="101" class="pesqopcao">101</div>
<div id="601" class="pesqopcao">601</div>
<div id="901" class="pesqopcao">901</div>
<span id="z"></span>
&#13;
&#13;
&#13;