问题
I'm trying to create a Fanorona game. http://canapin.com/web/fanorona
One of my jQuery selector doesn't work as intended.
After moving a blue stone by clicking it then clicking on a green space, the active player (var activePlayer) changes from "blue" to "red".
$("#board").on("click", "[data-color='"+activePlayer+"']", function(){
console.log(activePlayer);
console.log($(this).attr("data-color"));
When the active played is "red" and I click on a red stone (data-color="red"), it does nothing. when I click on a blue stone, the first console.log displays "red", but the second one displays "blue", which puzzles me because my selector uses the activePlayer variable which contains "red".
Any idea ? Here is the full js code if it can help : http://pastebin.com/7UYks2Z1
Fanorona rules : https://en.wikipedia.org/wiki/Fanorona
回答1:
The problem is that you're always binding on data-color=blue
because the variable activePlayer
is 'blue' when the script starts.
You can solve it by binding an event to both cases. Like this:
$("#board").on("click", "[data-color='red']", function(){
activeStone["x"] = $(this).attr("data-x");
activeStone["y"] = $(this).attr("data-y");
checkPossibleMoves(activeStone["x"],activeStone["y"], "red");
});
$("#board").on("click", "[data-color='blue']", function(){
activeStone["x"] = $(this).attr("data-x");
activeStone["y"] = $(this).attr("data-y");
checkPossibleMoves(activeStone["x"],activeStone["y"], "blue");
});
An alternative would be binding without a data-color
attribute and retrieving it in your callback.
来源:https://stackoverflow.com/questions/31562875/jquery-selector-targetting-a-dynamic-attribute-not-working