如何在单击 jQuery 函数中正确传递 $(this)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9563479/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 10:59:05  来源:igfitidea点击:

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

jqueryclickthis

提问by wayfare

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

我正在尝试在 jQuery 中制作一个 tictactoe 项目,但遇到了一个大问题......

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.

磁贴在<td>标签中,我试图这样做,以便当用户单击磁贴时,它会调用“标记”函数。

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

如果我们现在查看“标记”函数,$(this)它旨在成为<td>调用该函数的节点。

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

但是,它没有做任何事情,所以我检查了控制台,显然$(this)它包含 DOM Window 对象。

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

无论如何,我可以将正确的类型发送$(this)到“标记”功能吗?

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");
    }

回答by Tomalak

You code does not follow the right principles.

你的代码没有遵循正确的原则。

$(function(){
    var TURN_X = "X",
        TURN_O = "O", 
        turn   = TURN_O,
        $listCells = $("td");

    function marked() {        // define event handler
        var $this   = $(this),
            tileNum = $this.attr("id");

        if ( !($this.hasClass("marked") ) {
            $this.addClass("marked").text(turn);
            turn = (turn == TURN_X) ? TURN_O : TURN_X;
        }
    }

    $listCells.click(marked);  // attach event handler
});
  1. Wrap everything in the document.ready function. Avoid global variables wherever possible.
  2. Make use of the fact that jQuery manages thisfor you. thiswill always be what you expect if you pass callback functions directly instead of calling them yourself.
  1. 将所有内容包装在 document.ready 函数中。尽可能避免使用全局变量。
  2. 利用 jQuerythis为您管理的事实。this如果您直接传递回调函数而不是自己调用它们,那么将永远是您所期望的。

回答by Hadas

Send the element which fire the event to the function like that:

将触发事件的元素发送到函数,如下所示:

$("td").click(function(){
        marked($(this));
        return false;
    });

and in the function:

并在函数中:

function marked(td)
{
     console.log($(td));  
     $(td).addClass("marked");
     //....
}

回答by Daphoque

More simply, use bind :

更简单地,使用 bind :

$(".detailsbox").click(function(evt){
   test.bind($(this))();
});
function test()
{
   var $this = $(this);
}

回答by francisco.preller

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");
}

回答by adeneo

$(document).ready(function(){
    var TURN_X = false,
        TURN_O = true,
        turn = false,
        listCells = $.makeArray($("td"));

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

    function marked(arr, self) {
        $(self).addClass("marked");

        if(turn == TURN_X) {
            self.innerHTML = "X";
            turn = false;
        }else{
            self.innerHTML = "O";
            var tileNum = self.id;
        }
    }
});

回答by Guffa

You can use the callmethod to specify the scope for the function:

您可以使用该call方法指定函数的作用域:

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

Now the markedfunction can access the clicked element using the thiskeyword.

现在该marked函数可以使用this关键字访问被点击的元素。

回答by Sarfraz

You need to pass $(this)to your function:

您需要传递$(this)给您的函数:

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

And modify your function like this:

并像这样修改你的函数:

function marked(arr, that)
{
  that.addClass("marked");

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

  var tileNum = that.attr("id");
}

回答by quzary

try this:

尝试这个:

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



function marked(o,arr)
{
...