How to pass $(this) properly in click jQuery funct

2019-06-15 01:01发布

I am trying to make a tictactoe project in jQuery and I am having a major problem...

The tiles are in <td> tags and I am trying to make it so that when the user clicks the the tile, it calls the "marked" function.

If we now look into the "marked" function, $(this) is intended to be the <td> node that the function was called from.

However, it wasn't doing anything so I checked the console and apparently $(this) was containing the DOM Window object.

Is there anyway I can send the right kind of $(this) to the "marked" function?

Thank you!

<script type="text/javascript">

    var TURN_X = false;
    var TURN_O = true;

    var turn = false;  // this is to see whos turn it is.

    $(document).ready(function(){

        var listCells = $.makeArray($("td"));
        $("td").click(function(){marked(listCells)});   //THIS IS WHERE I HAVE PROBLEMS
        return false;
    });

    function marked(arr)
    {
        console.log($(this));  // THIS CONSOLE LOG RETURNS "DOM Window"
        $(this).addClass("marked");

        if(turn == TURN_X)
        {
        this.innerHTML = "X";
        turn = false;
        }
        else
        this.innerHTML = "O";

        var tileNum = $(this).attr("id");
    }

8条回答
成全新的幸福
2楼-- · 2019-06-15 02:08

Try:

$("td").click(function(event){
    marked(listCells, $(this));
});

Then:

function marked(arr, sel) {
    console.log($(this));
    sel.addClass("marked");

    if(turn == TURN_X) {
        this.innerHTML = "X";
        turn = false;
    } else {
        this.innerHTML = "O";
    }
    var tileNum = $(this).attr("id");
}
查看更多
The star\"
3楼-- · 2019-06-15 02:08

try this:

$(function(){
    var listCells = $.makeArray($("td"));
    $("td").click(function(){marked($(this),listCells)});  
});



function marked(o,arr)
{
...
查看更多
登录 后发表回答