2

I am writing a small library for internal use in a project that I am working on, I am an amateur Javascript developer, so mind my mistakes please.

I have written a small html file as well as javascript below it goes,

<html>
 <head>
  <script>
    var prc = {
      cng : function(evt){
           console.log(evt);
      }
    }
  </script>
 </head>
 <body>
   <input type='text' id='prc' onkeydown="prc.cng(window.event)"/>
 <body>
</html>

I tried executing this in Firefox and Chrome, not in IE Still,

When I am trying in Firefox, it gives this error "TypeError: prc.cng is not a function", and when trying in chrome it gives the "Uncaught TypeError: Object #<HTMLInputElement> has no method 'cng'".

I tried searching for this in StackOverflow, but the issues they are facing is quite different from what I am facing. Almost most of the issues faced were with jQuery involved, here please note that I am not using any kind of library and writing with plain old Javascript.

Any Help would be appreciated to enhance my understanding of the issue.

4

2 回答 2

2

Having an element with an id that is the same as an existing JS variable is blatting the content of the variable and replacing it with a reference to the element.

The quick solution is to change either the variable name or the element id.


A more robust solution would be to keep all your data in as narrow a scope as possible. If you don't desperately need it to be global, then don't make it global and it won't be over-writable from outside the script.

Since, using intrinsic event attributes, you can only refer to variables in <script> elements if they are global, this is also a good time to stop using them and move to something modern.

// Self-executing anonymous function expression used to limit scope
(function () { 

    // Locally scoped prc that won't clash with the element
    var prc = {
      cng : function(evt){
           console.log(evt);
      }
    }

    // Event handler binding
    document.getElementById('prc').addEventListener('keydown', function (evt) {
        prc.cng(evt)
    });

}());

Note that this script doesn't delay execution until load or domReady so place it after the input so that the input exists when the attempt to find the event handler happens.

于 2013-05-16T08:20:52.273 回答
0

I have found the answer to my own question, thanks to @Barmar, who has been instrumental in making me understand the problem.

When i define any element in html like this

<input type='text' id='test' onkeydown='test.fn()'/>

It means that an object is created by the browser for the same. So If I have javascript written which clashes with the id, that won't be accessible anywhere in that page.

<script>
  var test = {
    fn : function(){
       console.log('test');
     }
  }
</script>

So Ideally either rename the id, or rename the object.

于 2013-05-16T08:22:21.553 回答