我试图创建一个输入ID列表并在数组中使用它,使它们只读 - 但结果是错误 ->“无法读取null的属性'readOnly'”。 你能给我一个提示我应该改变什么吗?
script language="javascript" type="text/javascript">
$(document).ready(function () {
$(function(){
var index, len;
$.get('/SomeList.txt', function(data){
var SomeList = data.split('\n');
for (index = 0, len = SomeList.length; index < len; index++) {
document.getElementById(SomeList[index]).readOnly = true;
}
});
});
});
</script>
txt 文件包含输入 ID 的名称:
TextFieldName
TextFieldEmail
TextFieldDepartment
TextFieldOffice
最佳答案
假设您有一些具有给定 ID 的元素,您必须先检查该元素是否存在,然后再执行
document.getElementById(SomeList[index]).readOnly = true;
所以将该行替换为
var myElement = document.getElementById(SomeList[index]);
if(myElement == null) {
return;
}
myElement.readOnly = true;
这应该像下面的示例一样工作,其中 ID 来自数组,而第二个 ID 由于 xxxxx
而不会匹配,因此它不是只读的。但其他人都是。
var dataArray = [
'TextFieldName',
'TextFieldEmailxxxxx',
'TextFieldDepartment',
'TextFieldOffice'
];
dataArray.forEach(function(id){
var myElement = document.getElementById(id);
if(myElement == null) {
return;
}
myElement.readOnly = true;
});
<input id="TextFieldName" type="text">
<input id="TextFieldEmail" type="text">
<input id="TextFieldDepartment" type="text">
<input id="TextFieldOffice" type="text">
关于javascript - 数组中的 getElementByID.readOnly,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47336161/