2014-09-01 540 views
0

我無法找到解決方案(或者我錯過了它),所以我嘗試從您那裏獲得答案。未捕獲的類型錯誤無法讀取未定義的屬性'長度'

我有以下的html:

<input name="title" type="text" id="title" size="69" maxlength="30" onmouseout="CheckFieldLength(title, 'charcount2', 'remaining2', 30);" onkeydown="CheckFieldLength(title, 'charcount2', 'remaining2', 30);" onkeyup="CheckFieldLength(title, 'charcount2', 'remaining2', 30);"/></td> 

我試圖讓輸入字段的字符長度如下:

<span id="charcount2">0</span> characters entered | <span id="remaining2">140</span> characters remaining 

JS文件在以下做技巧:

function CheckFieldLength(fn,wn,rn,mc) { 
    var len = fn.value.length; 
    if (len > mc) { 
     fn.value = fn.value.substring(0,mc); 
     len = mc; 
    } 
    document.getElementById(wn).innerHTML = len; 
    document.getElementById(rn).innerHTML = mc - len; 
} 

但是,我只是不斷收到以下錯誤:

uncaught typeerror cannot read property 'length' of undefined 

你有什麼想法如何解決這個問題?

回答

1

使用該函數是這樣

CheckFieldLength(this, 'charcount2', 'remaining2', 30); 
0

使用代替冠軍

<input name="title" type="text" id="title" size="69" maxlength="30" 
    onmouseout="CheckFieldLength(this, 'charcount2', 'remaining2', 30);" 
    onkeydown="CheckFieldLength(this, 'charcount2', 'remaining2', 30);" 
    onkeyup="CheckFieldLength(this, 'charcount2', 'remaining2', 30);"/> 

'this'關鍵字會將當前元素作爲對象傳遞給javascript函數,剩下的部分將會照顧到您所擁有的功能。

+0

謝謝,這只是工作真棒! :) – 2014-09-01 23:43:37

相關問題