Javascript onclick事件的Javascript“this”参考不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12820724/
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-24 08:33:55  来源:igfitidea点击:

Javascript "this" reference for onclick event not working

javascriptthis

提问by Tomcatom

I'm trying to call a function with the "onclick" event as so:

我正在尝试使用“onclick”事件调用一个函数,如下所示:

<td id="A1" onclick="move()" class="white"></td>
<td id="A2" onclick="move()" class="painted bp"></td>
<td id="A3" onclick="move()" class="white"></td>

In the function itself, i refer to "this":

在函数本身中,我指的是“这个”:

function move(e){
    var myId = this.id;
    alert("myId");
}

When I run the whole thing, the alert says 'undefined'. When I try alert(this)I get [object window]. I'm working with IE9, btw. Thanks

当我运行整个过程时,警报显示“未定义”。当我尝试时,alert(this)我得到 [对象窗口]。我正在使用 IE9,顺便说一句。谢谢

回答by xdazz

thisis the windowobject in your code.

thiswindow代码中的对象。

You could pass thisas the parameter.

你可以this作为参数传递。

<td id="A1" onclick="move(this)" class="white"></td>

then:

然后:

function move(ele){
    var myId = ele.id;
    alert("myId");
}

回答by Shadow Wizard is Ear For You

When calling a function from an event handler, its thisisn't set by the handler (though you can pass thisfrom the handler per Xdazz's answer, or set thisper Kyle's answer). Another approach is to extract the sender element from the event object associated with the event:

从事件处理程序调用函数时,它this不是由处理程序设置的(​​尽管您可以this根据 Xdazz 的回答从处理程序传递,或this根据 Kyle 的回答进行设置)。另一种方法是从与事件关联的事件对象中提取发送者元素:

function move(e) {
    if (!e)
        e = window.event;
    var sender = e.srcElement || e.target;

    //maybe some nested element.. find the actual table cell parent.
    while (sender && sender.nodeName.toLowerCase() != "td")
        sender = sender.parentNode;

    var myId = sender.id;
    alert(myId);
}
?

You also must pass the event explicitly:

您还必须明确传递事件:

onclick="move(event)"

Note that when the table cell has nested elements they will be the "sender" thus to grab the desired element (which is the table cell) you have to traverse upwards. To avoid all this headache see below how to attach the handlers through code.

请注意,当表格单元格具有嵌套元素时,它们将成为“发送者”,因此要获取所需的元素(即表格单元格),您必须向上遍历。为了避免所有这些令人头疼的问题,请参阅下文如何通过代码附加处理程序

Live test case.

现场测试用例

That said, better practice would be to bind the click event through code instead of inline - don't mix HTML with JavaScript. To achieve this, have such code:

也就是说,更好的做法是通过代码而不是内联来绑定点击事件——不要将 HTML 与 JavaScript 混合。为了实现这一点,有这样的代码:

window.onload = function() {
    var arrCells = document.getElementsByTagName("td");
    for (var i = 0; i < arrCells.length; i++) {
        var oCell = arrCells[i];
        if (oCell.id && oCell.id.substr(0, 1) == "A") {
            oCell.onclick = move;
        }
    }
}

With the above code in place, you can remove the inline onclick=calls from the HTML and keep your original function - the thiswill point to the clicked table cell.

有了上面的代码,您可以onclick=从 HTML 中删除内联调用并保留原始函数 -this将指向单击的表格单元格。

Updated fiddle.

更新了小提琴

回答by Kyle

<td id="A1" onclick="move.call(this)" class="white"></td>

Now thiswill refer to the tdelement in your movefunction.

现在this将引用tdmove函数中的元素。

回答by Karl Rosaen

Try using the event target instead to get the dom element you are looking for:

尝试使用事件目标来获取您要查找的 dom 元素:

function move(e) {
  alert(e.target);
}