Trying to bind click action on table td

2019-07-07 19:38发布

I'm trying to add a click action to the cells of an html table.

Here's my Javascript :

$(document)
    .ready(

function () {
    function setColor(cell) {
        var cssRed = {
            "color": '#ff0000'
        }
        var cssBlue = {
            "color": '#0000ff'
        }
        if (cell.css('color') == '#ff0000') cell.css(cssBlue);
        else cell.css(cssRed);
    }
    $('td').click(function () {
        setColor($(this));
    });
});

And here's my HTML

    <table style="text-align: center" border='1'>
    <tbody>
        <tr>
            <td>Data</td>
            <td>Data</td>
            <td>Data</td>
        </tr>
        <tr>
            <td>Data</td>
            <td>Data</td>
            <td>Data</td>
        </tr>
        <tr>
            <td>Data</td>
            <td>Data</td>
            <td>Data</td>
        </tr>
    </tbody>
</table>

Which is supposed to change the color of the text within the clicked cell. I'm trying to make something similar to the grid in http://whenisgood.com

Although, for some reason, it keeps entering the else statement of the if (in the setColor method). So apparently this comparison cell.css('color') == '#ff0000' fails every time. What did I do wrong here?

edit: I made an alert of the cells.css('color') and here's the output : at first rgb(11,4,0)

and then after clicking a second time : rgb(255,0,0)

edit2: At first I tried assigning the colors as blue and red literally. However it wouldn't work (even if I was comparing with blue and red). I guess Javascript won't marshall red in Hex or RGB, right?

edit3: If you downvote, please let me know why, I'll try to update the question so it gets better.

2条回答
We Are One
2楼-- · 2019-07-07 19:57

I am assuming the default color of the td is red.

So just set your CSS to

td{color:#ff0000;}
td.highlight{color:#0000ff;}

and the script

$(document).ready(function () {
    function setColor(cell) {
        $(this).toggleClass('highlight');
    }
    $('td').click(setColor);
});

Demo at http://jsfiddle.net/zqytM/

查看更多
倾城 Initia
3楼-- · 2019-07-07 20:03

Different browsers may return different values for colours as people have suggested.

jQuery's css() documentation confirms this.

Different browsers may return CSS color values that are logically but not textually equal, e.g., #FFF, #ffffff, and rgb(255,255,255).

So I would suggest relying on CSS classes instead:

CSS

.red {
    color: #ff0000;
}
.blue {
    color: #0000ff;
}

jQuery

$(document)
.ready(
        function() {
            function setColor(cell){
                var shouldSwitch = cell.hasClass("red");
                cell.toggleClass("red", !shouldSwitch);
                cell.toggleClass("blue", shouldSwitch);

            }
                $('td').click(function(){
                    setColor($(this));
                  });
            });

Here's a working demo.

查看更多
登录 后发表回答