-2

不知何故,我无法使 var “转向”改变。

--------------'#a3' 是一个 div-----------------

对于所有的代码去这里

这是一些 js/jquery:

var turn = 1;

if (turn === 1) {

//----------------------------red
if (da3 === false) {
    $('#a3').click(function () {
        $(this).css("background-color", "red");
        turn = 0;
    });
}

if (turn === 0) {

//----------------------------blue
if (da3 === false) {
    $('#a3').click(function () {
        $(this).css("background-color", "blue");
       turn = 1;
    });
}

这是我使用的一些CSS:

div {
display: inline-block;
background-color:grey;
width : 150px;
height: 150px;
}
4

3 回答 3

1

这是因为您只添加了一个只做一件事的事件处理程序。它不会神奇地添加另一个。

在点击事件中执行 if/else 逻辑。

于 2013-09-26T16:50:22.807 回答
0

您当前的代码结构如下:

var turn = 1;  // red turn first
if (turn === 1) {
    // assign click handlers for red moves
}
if (turn === 0) {
    // assign click handlers for blue moves
}

这样做的问题是,这里将使用的唯一单击处理程序是if (turn === 1)块中定义的处理程序。修改时不会重新评估代码,turn因此永远不会使用蓝色的单击处理程序。

相反,它应该看起来像这样:

var turn = 1;  // red turn first
// example click handler:
$('#a3').click(function () {
    // check whose turn it is *inside* of the click handler
    if (turn === 0) {
        $(this).css("background-color", "blue");
        turn = 1;
    } else {
        $(this).css("background-color", "red");
        turn = 0;
    }
});
// other click handlers like the above (or better yet, reuse the same function)
于 2013-09-26T16:52:54.170 回答
0

如果要通过单击 a3 元素来切换背景颜色,则需要在事件处理程序内部进行 if/else 检查:

bg_state = 0;

$('#a3').click(function () {
    if (bg_state===0) {
       $(this).css("background-color", "blue");
        bg_state=1;
    } else {
       $(this).css("background-color", "red");
        bg_state=0;
    }
});

http://jsfiddle.net/ADUV9/

事件处理程序的设置只执行一次,当页面加载时!

于 2013-09-26T16:53:01.563 回答