2014-01-07 33 views
0

我有一个简单的表单,某些字段通过JS设置为“只读”。为什么我不能使用点语法来访问表单元素id属性而不是关联arary

我也不是不明白的是为什么这条线在我的代码工作:

mainForm[readonlyElms[i].id].setAttribute("readonly", "readonly"); 

而这条线抛出了一个错误“遗漏的类型错误:无法读取属性‘0’的未定义”:

mainForm.readonlyElms[i].id.setAttribute("readonly", "readonly"); 

(简化的形式):

<form> 
<input type="text" id="fname"> 
<input type="text" id="lname"> 
<input type="text" id="dob"> 
<input type="tel" id="tel">  
</form> 

JS

var mainForm = document.forms[0]; 
var readonlyElms = [fname, lname, dob]; 
for (var i = 0, len = readonlyElms.length; 
i < len; 
i++) { 

     //this line does the job 
     //mainForm[readonlyElms[i].id].setAttribute("readonly", "readonly"); 

     //BUT why not this line??? 
     mainForm.readonlyElms[i].id.setAttribute("readonly", "readonly"); 
    } 

我努力说出问题标题,所以如果使用的术语不正确,请纠正。

谢谢

+0

由于表达'readonlyElms [I] .id'本身不是mainForm'的'的性质。它是一个返回_value_的表达式,它可能是'mainForm'的一个属性。 –

+1

你为什么不使用readonlyElms [i] .setAttribute()?此外,带有ID的元素会在id的名称下创建全局变量,这就是您可以如何访问readonlyElms数组中的输入。我想mainform.ID也会起作用。 – dandavis

回答

2

这些行做了非常不同的事情。

第一:

mainForm[readonlyElms[i].id].setAttribute("readonly", "readonly"); 

获取的readonlyElms[i]值,然后获得其id属性的值,然后使用该值来查找具有该名称上mainForm,然后就可以调用setAttribute

第二:

mainForm.readonlyElms[i].id.setAttribute("readonly", "readonly"); 

...看起来对mainForm名为readonlyElms属性,尝试从i从中获得与名称的属性,然后再尝试获取该对象的id,和然后尝试拨打setAttributeid的值。

这样做的原因是,两种语法不同的工作:

括号表示法允许括号内的任何表达式,计算该表达式,结果强制转换成字符串(如有必要),然后查找财产用该字符串定义的名称。

点符号使用文字您在代码中键入的属性名称。

因此,举例来说,obj.foo总是仰视上objfoo属性,而obj[foo]是仰视任何属性名称由foo变量(可以是"fluglehorn"或其他任何东西)举行。

有时例子帮助:

// These all look up the same property on the same object: 

// Dot notation and a property name literal 
obj.foo 

// Bracketed notation and a string literal 
obj["foo"] 

// Bracketed notation using a variable 
var f = "foo"; 
obj[f] 

// Bracketed notation using the result of a concatenation expression 
var o = "o"; 
obj["f" + o + o] 

// Bracketed notation using the result of a function call expression 
function bar() { 
    return "foo"; 
} 
obj[bar()] 
+1

谢谢。非常清楚。当我被允许时会接受。 – Andy

相关问题