onClick函数“this”返回窗口对象 [英] onClick Function "this" Returns Window Object
问题描述
如果我编写这样的元素:
< li onClick =alert(this.tagName)>< / li>
我得到LI。
然而,如果我这样做:
< li onClick = 富() >< /锂>
其中foo()是:
function foo(){alert(this.tagName); }
我得到undefined。
我不知道this应该如何处理附加功能。但是,我很困惑,因为这个没有提到元素,但显然默认为窗口。我无法弄清楚为什么会发生这种情况。
有没有人有解释?
那是因为你没有在JavaScript函数调用中传递对 this 的引用。 JavaScript函数中的 this 不指向与 onClick 示例中相同的对象。试试这个:
< li onClick =foo(this)>< / li>
函数foo(item){alert(item.tagName); }
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>
I get "LI."
However if I do this:
<li onClick="foo()"></li>
Where "foo()" is:
function foo(){ alert(this.tagName); }
I get "undefined."
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.
Does anyone have an explanation?
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屋!