jQuery:选择器定位动态属性不工作 [英] jQuery : selector targetting a dynamic attribute not working
问题描述
我正在尝试创建一个Fanorona游戏。
http://canapin.com/web/fanorona
I'm trying to create a Fanorona game. http://canapin.com/web/fanorona
我的一个jQuery选择器不按预期工作。
One of my jQuery selector doesn't work as intended.
通过点击蓝色石头,然后点击绿色空间,活动播放器(var activePlayer)从蓝色更改为红色。
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"));
当主动播放是红色,我点击红色石头(data-color =red),它什么都不做,当我点击一个蓝色的石头,第一个console.log显示红色,但第二个显示蓝色,这使我困惑,因为我的选择器使用activePlayer变量包含red。
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".
任何想法?
这是完整的js代码,如果它可以帮助: http://pastebin.com/7UYks2 Z1
Fanorona规则: https: //en.wikipedia.org/wiki/Fanorona
Fanorona rules : https://en.wikipedia.org/wiki/Fanorona
推荐答案
问题是你总是有约束力 data-color = blue
因为脚本启动时变量 activePlayer
是蓝色。
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");
});
一个替代方法是没有 data-color
属性并在回调中检索它。
An alternative would be binding without a data-color
attribute and retrieving it in your callback.
这篇关于jQuery:选择器定位动态属性不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!