我是第一次学习 Javascript。我正在制作井字游戏。这可能不是最好的编码方式,但我决定使用以下策略:
# 中的每个网格都是其自己的 div。如果一个 div 被“X”占据,它会添加一个新类“xClass”;同样,如果它被“O”占用,则它的新类是“oClass”。
我想编写一个名为 winCheck() 的函数,用于检查游戏中是否有任何获胜组合的类已更改为全 X 或全 O。我已经在 jQuery 中为 div 赋予了它们自己的变量.
var winningCombos = [
[box1, box2, box3],
[box4, box5, box6],
[box7, box8, box9],
[box1, box4, box7],
[box2, box5, box8],
[box3, box6, box9],
[box1, box5, box9],
[box3, box5, box7]
];
例如,如果 box1、box2 和 box3 都被 X 占用,则它们的类将更改为“xClass”,并且 X 获胜。我可以使用什么函数来验证他们的类是否已更改?
我尝试过以下方法:
if (winningCombos[i].children().className === "xClass") {
alert("Player 1 has won!");
我也在尝试 .hasClass() 方法,可以吗?
if (winningCombos[i].children.hasClass("xClass") === "true" {
alert("Player 1 has won!");
有人可以帮忙吗?
最佳答案
另一种方法是为每个获胜组合设置一个唯一的类别名称。因此框 1、2 和 3 将具有共享标识符类。
因此,根据二维数组判断,您最终会得到八个标识符类。
如果 div 允许为“X”、“O”或两者都不是。然后,您可以对标识符类执行迭代器,以查看是否有任何单个标识符触发了获胜条件。
// Giving the identifier 'tttX' as the class name, X being the unique
// Could make that an array itself. I am going for quick and dirty here
$(".board div").click(function(e){
var winningComboArrayLength = 8; // If the board went to 4x4 it would be 16
var winningConditionLength = 3;
for(var i = 0; i < winningComboArrayLength; i++){
if($("div.xClass.ttt" + i.toString()).length == winningConditionLength){
// X won logic
alert('X player won!');
}
else if($("div.oClass.ttt" + i.toString()).length == 3){
// O won logic
alert('O player won!');
}
}
});
现在我进一步研究它,您可以像这样从 jQuery 对象创建数组。
然后通过该数组以不同的方式检查获胜条件。
var winningCombos = [];
$(function(){ winningCombos = [
$('#box1,#box2,#box3'),
$('#box4,#box5,#box6'),
$('#box7,#box8,#box9'),
$('#box1,#box4,#box7'),
$('#box2,#box5,#box8'),
$('#box3,#box6,#box9'),
$('#box1,#box5,#box9'),
$('#box3,#box5,#box7')
];
$(".board div").click(function(e){
var winningConditionLength = 3;
var maxLength = 0;
for(var i = 0; i < winningCombos.length; i++){
if(winningCombos[i].filter('.xClass').length == winningConditionLength){
// X won logic
$('.result').text('X player won!');
}
else if(winningCombos[i].filter('.oClass').length == winningConditionLength){
// O won logic
$('.result').text('O player won!');
}
}
});
});
关于javascript - jQuery:检查元素是否具有类,然后执行函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34324046/