Javascript“this” onclick事件的参考不起作用 [英] Javascript "this" reference for onclick event not working
问题描述
我正在尝试使用onclick事件调用函数:
I'm trying to call a function with the "onclick" event as so:
<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>
在函数本身中,我指的是this:
In the function itself, i refer to "this":
function move(e){
var myId = this.id;
alert("myId");
}
当我运行整个事情时,警报显示未定义。当我尝试 alert(this)
时,我得到[对象窗口]。
我正在使用IE9,顺便说一句。
谢谢
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
推荐答案
从事件处理程序调用函数时,其此
不是由处理程序设置的(虽然你可以根据Xdazz的答案从处理程序传递这个
,或者设置这个
每凯尔的回答)。另一种方法是从与事件关联的事件对象中提取sender元素:
When calling a function from an event handler, its this
isn't set by the handler (though you can pass this
from the handler per Xdazz's answer, or set this
per Kyle's answer). Another approach is to extract the sender element from the event object associated with the event:
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.
这就是说,更好的做法是通过代码绑定点击事件而不是内联 - 不要将HTML与JavaScript混合使用。要实现这一点,请使用以下代码:
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:
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;
}
}
}
上面的代码已经到位,您可以从HTML中删除内联 onclick =
调用并保留原始函数 - 此
将指向点击表格单元格。
With the above code in place, you can remove the inline onclick=
calls from the HTML and keep your original function - the this
will point to the clicked table cell.
这篇关于Javascript“this” onclick事件的参考不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!