使用jquery切换类
我正在为类创建一个简单的瓦片游戏。我所试图做的是:使用jquery切换类
- 父DIV中的一个子类“广场”,如果点击,广场追加到类的父“空”
- 我需要的父项让孩子现在成为班级'空'和现在被占领的父级班'全'
目前我遇到的问题是孩子们继续追加班级'空',和该班不转换。
我看这里:Get all elements without child node in jQuery
这里:http://api.jquery.com/toggleclass/
,这里是我的代码笔:http://codepen.io/super996/pen/vyQyxN
// when page loads all parent divs are clickable to .empty class div
$('document').ready(function() {
for (let i = 0; i < $('.parent').children().length; i += 1) {
$('.square').click(function() {
$(this).appendTo('.empty');
});
}
});
$('parent:has(.full)').click(function (event) {
$(event.target).toggleClass('.empty', true);
});
});
if ($('.square').click === true) {
//parent of sqaure gets class empty and destination of square
//parent gets class full
}
编辑:我在尝试这个过程中他..
if ($('.full:first-child').click(function(){
$('.full:first-child').removeClass('.')
});
所以我你如何试图完成这个有点模糊,但它看起来像你想点击一个完整的瓷砖时,从.full
切换类.empty
和.full
类添加到空的瓷砖。为此,您可以通过委派事件的孩子尝试#board
尝试:
$(document).ready(function(){
var $board = $('#board'); //Cache the board
$board.on('click', 'div.full', function(){
$board.find('div.empty').removeClass('empty').addClass('full');
$(this).addClass('empty').removeClass('full');
});
});
这会帮助你没有做你整个指派;) 现在,所有你需要做的是找出其中从.addClass
和.removeClass
切换到.appendTo
和.empty
要了解,“找到类与全div和回调函数是交换。“为了尝试和解决问题,我进入了devtools,并使用javascript试图让父母和孩子们希望得到它。谢谢丹尼尔! –
是的,你明白了 – DanielC
这是我完整的javascript代码。
也许你可以试试这个
// when page loads all parent divs are clickable to .empty class div
$('document').ready(function() {
$('.square').click(function() {
var parent = $(this).parent('div');
$(this).appendTo('.empty');
$('.empty').addClass('full').removeClass('empty');
parent.addClass('empty').removeClass('full');
});
});
你的问题是明确的更换你的脚本。你的代码也很混乱/错误,比如你为什么需要'for(let i = 0; i
即将点击函数添加到我的所有广场 –
不需要for循环然后:'$('。square')'将选择dom中所有与square类相关的元素,然后您可以将事件附加到tham –