私は戦艦ゲームを作っていますが、私は現在自分のボートを置いています。私はクリックすることができるようにしたい、そして色を変えるグリッド上の1つの四角形。私は入れ子になったfor()ループを通して各タイルにイベントリスナーを追加し、関数が実行されるときに各ボタンを参照するようにしています。JavascriptでaddEventListener()を使用している問題
タイルのいくつかは、クリックすると色が変わりますが、他のものは色が変わっていません。また、どのような変更を行うことができますか、できないパターンはありません。 2〜3回、色が変わります。コードはここにあります。 (私はまた、カラーセレクターを追加しました)。
var x_client = 0;
var y_client = 0;
var battlefield_client = "";
for (y_client = 1; y_client < 11; y_client++) {
battlefield_client += "<tr>";
for (x_client = 1; x_client < 11; x_client++) {
battlefield_client += "<td onclick = '' class = 'tile' style='border: 3px solid black;' id=" + "cell_client_" + x_client + "_" + y_client + "><pre> </pre></td>";
}
battlefield_client += "</tr>";
}
$(document).ready(function() {
$("#tableGrid_client").html(battlefield_client); //loads table
for (y_client = 1; y_client < 11; y_client++) {
for (x_client = 1; x_client < 11; x_client++) {
boatStatusClient = document.getElementById('cell_client_' + x_client + "_" + y_client);
boatStatusClient.addEventListener("click", function(){boatGrid.placeBoat_client()});
}
}
document.getElementById("redButton").addEventListener("click", function(){boatGrid.colorSelect()});
document.getElementById("orangeButton").addEventListener("click", function(){boatGrid.colorSelect()});
document.getElementById("yellowButton").addEventListener("click", function(){boatGrid.colorSelect()});
document.getElementById("greenButton").addEventListener("click", function(){boatGrid.colorSelect()});
document.getElementById("blueButton").addEventListener("click", function(){boatGrid.colorSelect()});
document.getElementById("violetButton").addEventListener("click", function(){boatGrid.colorSelect()});
document.getElementById("brownButton").addEventListener("click", function(){boatGrid.colorSelect()});
document.getElementById("blackButton").addEventListener("click", function(){boatGrid.colorSelect()});
}); //This is for the color selector.
colorSelect : function() {
colorPick = event.target || event.srcElement;
colorPick = colorPick.id
console.log(colorPick);
if (colorPick == redButton) {
colorSelect = "red";
}
else if (colorPick == orangeButton) {
colorSelect = "orange";
}
else if (colorPick == yellowButton) {
colorSelect = "yellow";
}
else if (colorPick == greenButton) {
colorSelect = "green";
}
else if (colorPick == blueButton) {
colorSelect = "blue";
}
else if (colorPick == violetButton) {
colorSelect = "purple";
}
else if (colorPick == brownButton) {
colorSelect = "brown";
}
else if (colorPick == blackButton) {
colorSelect = "black";
}
console.log(colorSelect);
},
placeBoat_client : function() {
var demoColor = "orange"
var source_client = event.target.id;
console.log(source_client);
source_client.id = document.getElementById(source_client.id);
document.getElementById(source_client).style.backgroundColor = demoColor;
},
}