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"返回窗口对象


- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- 失败的 Canvas 360 jquery 插件 2022-01-01
- Fetch API 如何获取响应体? 2022-01-01
- addEventListener 在 IE 11 中不起作用 2022-01-01
- Flexslider 箭头未正确显示 2022-01-01
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- 400或500级别的HTTP响应 2022-01-01
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01