我有一些JavaScript代码会给出此错误
Uncaught TypeError: Cannot read property 'value' of undefined
码
var i1 = document.getElementById('i1'); var i2 = document.getElementById('i2'); var __i = {'user' : document.getElementsByName("username")[0], 'pass' : document.getElementsByName("password")[0] }; if( __i.user.value.length >= 1 ) { i1.value = ''; } else { i1.value = 'Acc'; } if( __i.pass.value.length >= 1 ) { i2.value = ''; } else { i2.value = 'Pwd'; }
这个错误是什么意思?
好像您的值之一,属性键为“值”是未定义的。在执行if语句之前测试i1,i2和__i是否已定义:
i1
i2
__i
var i1 = document.getElementById('i1'); var i2 = document.getElementById('i2'); var __i = {'user' : document.getElementsByName("username")[0], 'pass' : document.getElementsByName("password")[0] }; if(i1 && i2 && __i.user && __i.pass) { if( __i.user.value.length >= 1 ) { i1.value = ''; } else { i1.value = 'Acc'; } if( __i.pass.value.length >= 1 ) { i2.value = ''; } else { i2.value = 'Pwd'; } }