0

我正在尝试删除我的一个元素上的“功能”。

这是生成代码的 html/php:

        <table>
        <?php for($i = 0; $i < 10; $i++){ ?>
            <tr>
                <?php for($k = 0; $k < 10; $k++) {?>
                    <td>asd</td>
                <?php }?>
            </tr>
        <?php } ?>
    </table>

这是jQuery:

            $("td:not(done)").click(function(){
                $(this).addClass("done");
                if(blue){
                    $(this).css("background-color", "blue");
                    blue = false;
                } else {
                    $(this).css("background-color", "red");
                    blue = true;
                }
            });

尝试向已单击的 td 元素添加一个类,因此在第一次单击后它不起作用。但不能让它工作。

4

4 回答 4

2

更新代码

使用.hasClass()

$("td").click(function () {
    if (!$(this).hasClass('done')) {
        $(this).addClass("done");
        if (blue) {
            $(this).css("background-color", "blue");
            blue = false;
        } else {
            $(this).css("background-color", "red");
            blue = true;
        }
    }
});

你忘了.done课堂上添加

类选择器文档

$("td:not(.done)").click(function(){
          ^
                $(this).addClass("done");
                if(blue){
                    $(this).css("background-color", "blue");
                    blue = false;
                } else {
                    $(this).css("background-color", "red");
                    blue = true;
                }
            });
于 2013-09-11T08:00:29.590 回答
0

我会为此使用委托,因此每次单击时都会评估目标选择器:

$('table').on('click','td:not(.done)', function(){
        $(this).addClass("done");
        if (blue) {
            $(this).css("background-color", "blue");
            blue = false;
        } else {
            $(this).css("background-color", "red");
            blue = true;
        }
});
于 2013-09-11T08:09:07.687 回答
0

据我了解,td应该只能点击一次,所以你需要的是.one()

$("td").one('click', function () {
    $(this).addClass("done");
    if (blue) {
        $(this).css("background-color", "blue");
        blue = false;
    } else {
        $(this).css("background-color", "red");
        blue = true;
    }
});

或使用未完成过滤器的事件委托

$("table").on('click', 'td:not(.done)', function () {
    $(this).addClass("done");
    if (blue) {
        $(this).css("background-color", "blue");
        blue = false;
    } else {
        $(this).css("background-color", "red");
        blue = true;
    }
});
于 2013-09-11T08:03:59.630 回答
0

如果你真的不需要添加类,那么你可以使用“one”方法为点击事件添加一个处理程序,这样它只会执行一次

http://api.jquery.com/one/

    $("td").one("click",(function(){
        if(blue){
            $(this).css("background-color", "blue");
            blue = false;
        } else {
            $(this).css("background-color", "red");
            blue = true;
        }
    });
于 2013-09-11T08:05:22.567 回答