onClick 功能“this"返回窗口对象 [英] onClick Function "this" Returns Window Object

查看:22
本文介绍了onClick 功能“this"返回窗口对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 JavaScript 应用程序遇到了令人头疼的问题.

I've come across a head scratching issue with my JavaScript application.

如果我这样写一个元素:

If I write an element like this:

<li onClick="alert(this.tagName)"></li>

我得到LI".

但是,如果我这样做:

<li onClick="foo()"></li>

foo()"在哪里:

function foo(){ alert(this.tagName); }

我得到未定义".

我不知道this"在附加功能方面应该如何工作.但是,我很困惑,因为this"没有提取元素,而是显然默认为window".我不知道为什么会这样.

I am away how "this" is supposed to work in regards to attached functions. But, I am baffled because "this" is not picking up the element, but apparently defaulting to "window." I can't figure out why this is happening.

有人解释一下吗?

推荐答案

这是因为您没有在 JavaScript 函数调用中传递对 this 的引用.JavaScript 函数中的 this 引用的对象与 onClick 示例中的对象不同.试试这个:

That's because you aren't passing a reference to this in the JavaScript function call. this in the JavaScript function doesn't refer to the same object as in the onClick example. Try this instead:

 <li onClick="foo(this)"></li>

 function foo(item){ alert(item.tagName); }

这篇关于onClick 功能“this"返回窗口对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆