如何在 jquery 中添加 js var

How to add js var inside jquery

本文关键字:添加 js var jquery      更新时间:2023-09-26

不知何故,我无法使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;
}

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

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

如果要

通过单击 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/

事件处理程序的设置仅在页面加载时执行一次!

您当前的代码结构如下:

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)