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"返回窗口对象
基础教程推荐
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
- 如何在特定日期之前获取消息? 2022-01-01
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- 每次设置弹出窗口的焦点 2022-01-01
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
