检测文本输入

时间:2013-07-17 03:20:13

标签: javascript text detect

我想了解这个JS函数: JS Fiddle Demo

我基本上是从一本我想要学习的书中得到的。这本书被称为“JavaScript:The Definitive Guide”(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;
    }
  }
}

2 个答案:

答案 0 :(得分:0)

相关的HTML可能是:

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

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

但是,我不确定该函数正在做什么是有用的,或者所使用的监听器附件和分离方法是健壮的。但它可能有助于理解事件和听众的某些方面。

答案 1 :(得分: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>
相关问题