2012-08-12 98 views
1

我有代碼:JS - 檢查長度功能

function check($ile,$co,$gdzie) 
{ 
    if (document.forms.form.$co.value.length >= $ile){ 
    document.forms.form.$gdzie.focus(); 
    } 
} 

而且它不工作。錯誤(在谷歌瀏覽器檢查):

Uncaught TypeError: Cannot read property 'value' of undefined script.js:39 
check script.js:39 
onkeyup 

它是我的html代碼:

<p><label><?php echo TEL; ?>: <input type='text' name='tel' size='9' maxlength='9' onkeypress="keyPressNumb(event);" onKeyUp="check(9,'tel','pesel');"></label></p> 
<label><?php echo PESEL; ?>:<span class='red'>*</span> <input type='text' name='pesel' size='11' maxlength="11" onKeyUp="check11();" onkeypress="keyPressNumb(event);"></label></p> 
+3

嘗試'document.forms.form [$ co] .value.length',因爲通過點符號訪問對象的值時無法使用變量。 – mAu 2012-08-12 19:26:47

+0

Thx,它的工作;) – Quarties 2012-08-12 19:37:19

回答

1

嘗試document.forms.form[$co].value.length,如通過點符號訪問對象的值時,你不能使用一個變量。

在您的代碼中,js預計對象document.forms.form中的屬性$ co。當您想通過變量訪問某個屬性時,必須使用括號來訪問該屬性。

document.bar = "hello world"; 

var foo = "bar"; 
document.foo // undefined, because document has no property "foo" 
document[foo] // "hello world" 
+0

現在我明白,thx。我是新來的,我是最新的;) – Quarties 2012-08-12 19:55:15

+0

@Quarties不客氣。請閱讀[faq](http://stackoverflow.com/faq),因爲您似乎對於stackoverflow來說是新手。如果您發現這個答案有幫助,請考慮批准它。 – mAu 2012-08-12 20:02:54

+0

我知道,我忘了;)我現在糾正它! – Quarties 2012-08-12 20:07:47