2017-08-15 14 views
2

クリックする場所に応じて変数を増分したい。クリックした場所の分だけ減らすことができます。しかし、最初のインクリメントはzには格納されないので、2番目のインクリメントは最初のインクリメントで加算されず、2番目のインクリメントだけがポストされます。この増分を働かせるにはどうすればいいですか?クリック位置に基づいて異なる値のインクリメント

$(".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

定義されていません.IDそれが機能するようになりました。ありがとう!! – Adato

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

機能外部(varキーワードなし)グローバル変数として2-宣言する。 、3- $(この)のjQuery APIの使用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>

関連する問題