我正在尝试使用 Javascript 将输入字段设置为只读,如果它们不包含任何值,即如果它们为空。这是我的代码,我没有收到来自调试器的任何错误,但它只是拒绝工作,有人可以吗
//checkScore();
function checkScore(){
document.getElementById('score_row1').readonly = true;
var scores = document.getElementsByClassName("score_holder");
var i;
for(i=0; i<scores.length; i++){
if(scores[i].value!=null){
scores[i].readonly="readonly";
}
}
}
<!doctype html>
<html>
<head>
</head>
<body onload="checkScore()">
<table align="center" cellpadding="3">
<tr valign="baseline">
<td colspan="3" align="center" id="course_row25" value="EDU-101"><strong>EDUCATION COURSES</strong></td>
</tr>
<tr>
<td align="right">
<input name="course_row1" type="text" id="course_row1" title="EDU-101: Historical Foundation of Education" value="EDU-101" size="5" readonly="readonly" />
</td>
<td> </td>
<td>
<input type="text" value="30" size="5" class="score_holder" />
</td>
</tr>
<tr>
<td align="right" id="course_row1" name="course_row1" value="EDU-101">
<input name="course_row1" type="text" id="course_row1" title="EDU-101: Historical Foundation of Education" value="EDU-101" size="5" readonly="readonly" />
</td>
<td> </td>
<td>
<input type="text" size="5" class="score_holder" />
</td>
</tr>
<tr>
<td align="right" id="course_row1" name="course_row1" value="EDU-101">
<input name="course_row1" type="text" id="course_row1" title="EDU-101: Historical Foundation of Education" value="EDU-101" size="5" readonly="readonly" />
</td>
<td> </td>
<td>
<input type="text" value="10" size="5" class="score_holder" />
</td>
</tr>
</table>
</body>
</html>
最佳答案
首先,您的 HTML 中没有 id 为 score_row1
的元素,因此您的 js 将抛出错误并失败。
此外,该属性是readOnly
,而不是readonly
所以这个 scores[i].readonly="readonly";
应该是 scores[i].readOnly="readonly";
创建了一个工作演示 here
关于javascript - 使用 Javascript 将输入设置为只读,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42510801/