2013-07-17 52 views
-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; 
    } 
    } 
} 
+1

請花時間縮進您的代碼。沒有人想讀這個爛攤子。如果你需要我們的幫助,至少讓我們儘可能愉快。 – meagar

+0

請嘗試http://jsfiddle.net/arunpjohny/vP9kD/1/或http://jsfiddle.net/arunpjohny/vP9kD/2/ –

+0

Tks Arun,這對我很有幫助。 – HattrickNZ

回答

0

相關HTML可能是:

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

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

但是,我不知道什麼功能正在做的是有用的或聽者附件和使用分離方法是穩健的。但它對理解事件和聽衆的某些方面可能有用。

+0

嗨RobG,爲此,但不完全得到你的行爲。 – HattrickNZ

+0

答案會向ID * i0 *的頁面添加一個元素,然後在頁面加載完成後調用* forceToUpperCase *函數。該函數將偵聽器添加到元素的* input *和* propertychange *事件。 – RobG

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> 
+0

tks,但希望得到一個工作示例,我可以與Arun在上面完成的工作互動並看到工作。 – HattrickNZ

+0

已解決@HattrickNZ – KING