【问题标题】:Cannot read property from my document.forms [duplicate]无法从我的 document.forms 中读取属性 [重复]
【发布时间】:2017-08-03 09:27:24
【问题描述】:

我的页面上有这个js 代码:

var mail = 'idEmail';
value(mail);
//function returning the value of an input
function value(input){
  return eval('window.document.Search.'+input).value;
}

我有这个错误:

TypeError: Cannot read property 'idEmail' of undefined

为什么当我将return eval('window.document.Search.'+input).value; 更改为return eval('window.document.forms['Search'].'+input).value; 时它可以工作?

document.forms["general"]
or
document.forms[0]
or
document.general 

都一样

【问题讨论】:

标签: javascript


【解决方案1】:

在您的function 中,您试图访问undefined 对象的属性,实际上.Search 不是window.document 的属性,而是window.document.forms 的属性,而是像这样更改它:

function value(input){
  return window.document.forms.Search[input].value;
} 

注意:

最好避免使用eval,你可以在你的函数中去掉它。

【讨论】:

    【解决方案2】:

    因为你忘记了forms 部分:

    return eval('window.document.forms.Search.'+input).value;
    

    注意eval 是邪恶的。你不妨这样做:

    return document.forms.Search[input].value;
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-03-10
    • 1970-01-01
    • 2021-09-18
    • 2017-09-24
    • 2017-01-16
    • 1970-01-01
    • 1970-01-01
    • 2015-05-08
    相关资源
    最近更新 更多