-2

我试图理解这个 JS 函数: JS Fiddle Demo

我基本上是从一本我想从中学习的书中得到它的。这本书被称为“JavaScript:权威指南”(pg484)。但是该函数不包括它附带的 html。如果有人可以帮助我编写可以使这项工作的html,我将不胜感激,从而我可能能够更好地理解它是如何工作的。我已经通过上面的链接对此进行了尝试。

我真的不喜欢这本书这样做的方式。它发生了很多。我是新手,除了来这里尝试得到答案之外,有没有人有什么建议。

感谢任何帮助。

//Example 17-7. Using the propertychange event to detect text input
function forceToUpperCase(element) {
  if (typeof element === "string") element = document.getElementById(element);
  element.oninput = upcase;
  element.onpropertychange = upcaseOnPropertyChange;
  // Easy case: the handler for the input event
  function upcase(event) { this.value = this.value.toUpperCase(); }
  // Hard case: the handler for the propertychange event
  function upcaseOnPropertyChange(event) {
    var e = event || window.event;
    // If the value property changed
    if (e.propertyName === "value") {
      // Remove onpropertychange handler to avoid recursion
      this.onpropertychange = null;
      // Change the value to all uppercase
      this.value = this.value.toUpperCase();
      // And restore the original propertychange handler
      this.onpropertychange = upcaseOnPropertyChange;
    }
  }
}
4

2 回答 2

0
<!DOCTYPE html>
<html>
   <head>
      <script>
        var element = document.getElementbyId(Java_C#);
         function forceToUpperCase(element) { 
           if (typeof element === "string") element = document.getElementById(element);    
              element.oninput = upcase;
              element.onpropertychange = upcaseOnPropertyChange;
        // Easy case: the handler for the input event

         function upcase(event) { this.value = this.value.toUpperCase(); }
        // Hard case: the handler for the propertychange event

         function upcaseOnPropertyChange(event) {
         var e = event || window.event;

        // If the value property changed
         if (e.propertyName === "value") {

        // Remove onpropertychange handler to avoid recursion
         this.onpropertychange = null;

       // Change the value to all uppercase
         this.value = this.value.toUpperCase();

      // And restore the original propertychange handler
        this.onpropertychange = upcaseOnPropertyChange;
    }
  }
} 
      </script>
   </head>
<body>
  <p id="Java_C#">
     Public static void main{}
  </p>
</body>
</html>
于 2013-07-19T13:32:12.547 回答
0

相关的 HTML 可能是:

<input type="text" id="i0">

<script>
  window.onload = function() {
    forceToUpperCase('i0')
  }
</script>

但是,我不确定该函数的用途是否有用,或者使用的侦听器附件和分离方法是否可靠。但它可能有助于理解事件和侦听器的某些方面。

于 2013-07-17T04:06:37.163 回答