我如何指定哪个表单自动填充而不给每个输入一个唯一的id?我有唯一的表单id。
我正在处理现有的代码,所以我不能改变输入id。
<a href="#" onClick="autoFill(); return true;" >Click to Autofill</a>
<form id="form1">
<p>
<label>Text Input: </label>
<input type="text" id="input1">
<label>Text Input: </label>
<input type="text" id="input2">
</p>
</form>
<a href="#" onClick="autoFill(); return true;" >Click to Autofill</a>
<form id="form2">
<p>
<label>Text Input: </label>
<input type="text" id="input1">
<label>Text Input: </label>
<input type="text" id="input2">
</p>
</form>
<a href="#" onClick="autoFill(); return true;" >Click to Autofill</a>
<form id="form3">
<p>
<label>Text Input: </label>
<input type="text" id="input1">
<label>Text Input: </label>
<input type="text" id="input2">
</p>
</form>
<script type="text/javascript">
function autoFill() {
document.getElementById('input1').value = "15";
document.getElementById('input2').value = "12";
}
</script>
您只需要正确地定位元素。这应该对你有用
function autoFill(formID) {
document.querySelector(`#${formID} #input1`).value = "15";
document.querySelector(`#${formID} #input2`).value = "12";
}
<a href="#" onClick="autoFill('form1'); return true;">Click to Autofill</a>
<form id="form1">
<p>
<label>Text Input: </label>
<input type="text" id="input1">
<label>Text Input: </label>
<input type="text" id="input2">
</p>
</form>
<a href="#" onClick="autoFill('form2'); return true;">Click to Autofill</a>
<form id="form2">
<p>
<label>Text Input: </label>
<input type="text" id="input1">
<label>Text Input: </label>
<input type="text" id="input2">
</p>
</form>
<a href="#" onClick="autoFill('form3'); return true;">Click to Autofill</a>
<form id="form3">
<p>
<label>Text Input: </label>
<input type="text" id="input1">
<label>Text Input: </label>
<input type="text" id="input2">
</p>
</form>
你也可以试试
<a href="#" onClick="autoFill('form1'); return true;">Click to Autofill</a>
<form id="form1">
<p>
<label>Text Input: </label>
<input type="text" id="input1">
<label>Text Input: </label>
<input type="text" id="input2">
</p>
</form>
<a href="#" onClick="autoFill('form2'); return true;">Click to Autofill</a>
<form id="form2">
<p>
<label>Text Input: </label>
<input type="text" id="input1">
<label>Text Input: </label>
<input type="text" id="input2">
</p>
</form>
<a href="#" onClick="autoFill('form3'); return true;">Click to Autofill</a>
<form id="form3">
<p>
<label>Text Input: </label>
<input type="text" id="input1">
<label>Text Input: </label>
<input type="text" id="input2">
</p>
</form>
<script type="text/javascript">
function autoFill(formID) {
const formEle = document.getElementById(formID);
const inputs = formEle.getElementsByTagName('input')
// convert to array
const inputsArr = Array.from(inputs);
for (const input in inputsArr)
inputsArr[input].value = "15";
}
</script>