jQuery:如果用户单击与被单击元素的 class 匹配,则删除 class 元素

jQuery: Remove class of elements on user click if it's a match with the class of the clicked element

我是一名新的网络开发人员(学生),正在尝试使用 jQuery/JavaScript 制作 Tic Tac Toe 游戏的变体(基本上是具有更多网格的更大版本的 Tic-Tac-Toe!)在最后一点功能上遇到麻烦。

基本上,它是 3x3 网格的 3x3 网格。当玩家 select 在其中一个小格子上划出一个方格时,该小方格在单个格子上的位置对应于下一位玩家必须在其上玩的大格子。

基本上,下一位玩家可以放置标记的位置有限,我希望将 class 的 'inactive' 添加到玩家无法放置的所有方块中 select。我想删除玩家可以 select 的方块上的那个 class。每回合,不同的方块都会移除不活动的 class(取决于玩家可以玩的地方)。

我尝试 solution/logic 是这样的:每个方块有三个 classes,两个数字和 'square'(后者出于样式原因)。第一个数字对应于它在其单独的 9x9 网格(1 到 9)上的位置,第二个数字对应于它的网格在更大的 9x9 网格方向上的位置(也是 1 到 9)。因此,位于 9x9 大网格左上角的网格左上角的小方块将具有 classes '1,'(它在 9x9 小网格中的位置)'square,' 和 '1'(它的网格在更大的 9x9 方向内的位置)。它旁边的第二个方块将有 classes '2 square 1'。它旁边网格上的方块的最后一个数字都是“2”class。

在玩家点击时,我基本上希望 jQuery 在每个方块上放置一个 'Inactive' class,return 第一个数字 class单击的正方形(对应于其在 9x9 小网格中的位置的数字)并删除第二个数字 class 与单击的正方形的 [=56] 相匹配的正方形上的 'Inactive' class =]ed 第一个数字 class.

所以当玩家在方块上放置 X 或 O 时: 1)在游戏板上的每个方块上添加非活动状态,这样下一个玩家就不能到处玩 2) Return被点击方块的第一个数字class。 3) 从游戏板上所有与步骤 2 中的 returned 值匹配的方块中移除非活动 class。 4) 下一位玩家放置他们的标记并重复。

我不知道这是否对任何人有意义,但这是相关的代码(定义了玩家放置标记时发生的情况):

        ticTacToe.placeMarker = function($square){
        //don't do anything if the square is already taken
        if ($square.hasClass('inactive')){
            return;
        }
      // puts an X or an O on the board
      // and marks the square as unavailable

        $square.html(ticTacToe.currentPlayer).addClass('inactive');

      // makes all squares unavailable
        ticTacToe.$squares.addClass('inactive');

      // returns the relevant (first) part (the number corresponding to its position in its individual grid) of the class of the clicked-on square (I know this part works because I console-logged it) 
        var myClass = $square.html(ticTacToe.currentPlayer).attr("class");
        var classSpecific = myClass.slice(0,1);
        return (classSpecific);

      // this is supposed to check if any element with the class 'square' (so any square) has the class corresponding to the returned value in the last step, and remove the Inactive class from it if it does. It looks messy when I eyeball it. It's probably wrong. 
        ('.square').hasClass(classSpecific).removeClass('inactive');

我想知道是否有人可以帮助我(也许我的语法搞砸了?也许我必须将它分成更多的步骤?也许我必须(希望不要)使用正则表达式)如果我设法让这个工作。它不必使用我的 logic/method,只要功能存在即可。提前致谢。我只 post 编辑了我认为相关的部分代码,但如果需要,我也可以 post 其他部分。

已解决

通过删除我 returning class特定变量所在的行,我的函数可以正常工作。

最后一行不正确,应该是

$('.square').hasClass(classSpecific).removeClass('inactive');

而不是

('.square').hasClass(classSpecific).removeClass('inactive');

查看网络上的 jQuery 教程可能会有用,正如我们从 jQuery selector documentation 中看到的那样,您可以从 jQuery构造函数。

jQuery API docs jQuery() — 也可以写成 $() — 在 DOM 中搜索与提供的选择器匹配的任何元素并创建一个新的jQuery 引用这些元素的对象:

然后您可以对这些元素执行操作,例如更改 CSS class,我认为这是您需要的 CSS class selector documentation 上的示例。它将红色边框添加到具有 .myClass class

的任何 DOM 元素
$( ".myClass" ).css( "border", "3px solid red" );