2017-08-15 49 views
2

我希望变量根据点击位置增加。然后能够减少它被点击的地方。然而,第一个增量没有存储在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>

回答

1

需要声明的变量jQuery的外部单击事件为它点击之间持续存在。

另外,第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

现在的作品。谢谢 !! – Adato

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

2-声明变量作为全局(无var关键字)之外的功能。 jQuery的API的 3- $没有定义(这).ID使用ATTR方法

$(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); 
 
} 
 
} 
 
}); 
 
});
.pesqopcao{background-color:white;}
<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>