if语句对我来说是有意义的,如果被点击的元素 = class.piece然后执行click方法来切换类。
添加了html。只是试图操纵.piece领域
Home.HighlightBackground = function ()
{
if(element.click = $(".piece"))
{
$(this).click(function()
{
$(this).toggleClass("highlighted");
}
)}
}
<html>
<div class="row">
<div class="cell piece black"></div>
<div class="cell piece black"></div>
<div class="cell piece black"></div>
<div class="cell piece black"></div>
<div class="cell piece black"></div>
<div class="cell piece black"></div>
<div class="cell piece black"></div>
<div class="cell piece black"></div>
</div>
//jQuery used to create the cells and their backgrounds
var cells = $(".cell");
var colorCount = 0;
for (var i = 0; i < cells.length; i++)
{
var cell = $(cells[i]);
var isDark = colorCount % 2 == 0;
var isNextRow = (i + 1) % 8 == 0;
colorCount += isNextRow ? 2 : 1;
cell.css("background-color", isDark ? "navy" : "white");
答案 0 :(得分:1)
正确的方法是:
$(".piece").click(function() {
$(this).toggleClass("highlighted");
});
要更改背景颜色,请添加CSS,如:
.highlighted {
background-color: yellow !important;
}
答案 1 :(得分:0)
试试此代码
$("body").click(function(){
var elem = $(this);
if(elem.hasClass("piece")){
elem.toggleClass("highlighted");
}
});