onClick Function quot;thisquot; Returns Window Object(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"返回窗口对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:onClick 功能“this"返回窗口对象
基础教程推荐
- 原生拖动事件后如何获取 mouseup 事件? 2022-01-01
- Bootstrap 模态出现在背景下 2022-01-01
- npm start 错误与 create-react-app 2022-01-01
- Bokeh Div文本对齐 2022-01-01
- 如何添加到目前为止的天数? 2022-01-01
- 在 contenteditable 中精确拖放 2022-01-01
- 即使用户允许,Gmail 也会隐藏外部电子邮件图片 2022-01-01
- Fabric JS绘制具有活动形状的多边形 2022-01-01
- 检查 HTML5 拖放文件类型 2022-01-01
- fetch 是否支持原生多文件上传? 2022-01-01
