onClick Function “this” Returns Window Object

后端 未结 5 1488

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

If I write an element like this:

  • 5条回答
    •  -上瘾入骨i
      2020-12-01 10:29

      Another option, so you don't have to pass this as a param, is to use call or apply. It's a built in mechanism to set the value of this within a function. Though I would point out, adding your event handlers directly to your html is a bit antiquated. You may want to check out a JS framework for event delegation (jQuery, Prototype, Dojo, YUI, etc.).

      fiddle: http://jsfiddle.net/bboone/Q2CkV/2/

      HTML

      test
      test2

      JS

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

    提交回复
    热议问题