如果没有id,在网站上用JavaScript填写输入字段?
Fill in a input field on a website with JavaScript if it has no id?
如果没有 id,如何在 JavaScript 的网站上填写输入字段?示例:
<input type="text" placeholder="First Name" value="" class="someclass">
<input type="text" placeholder="Last Name" value="" class="someclass">
我只想填写第一个输入框。
如果它有一个 ID,我就可以 document.getElementById
...
class 和类型被网站上的几个输入字段使用。我能以某种方式使用占位符吗?
只需 select 它与 document.querySelector('input.someclass')
编辑
如果您网站上输入的顺序和数量始终相同,请执行以下操作:
const inputs = document.querySelectorAll('input')
您可以从 querySelectorAll returns 的数组中选择输入,或者循环遍历数组来输入值。
const inputs = document.querySelectorAll('input');
const valuesToInput = [1,2,3,4,5,6,7,8,9];
for(let i = 0; i < inputs.length; i += 1) {
inputs[i].value = valuesToInput[i];
}
如果您为表单和输入添加 属性 "name",您可以通过以下方式使用它:
<form name="myForm">
<input type="text" name="myText">
<button onclick="addText(myForm)">Add Text</button>
</form>
在javascript中:
function addText(myForm){
myForm.myText.value = 'some text';
}
如果没有 id,如何在 JavaScript 的网站上填写输入字段?示例:
<input type="text" placeholder="First Name" value="" class="someclass">
<input type="text" placeholder="Last Name" value="" class="someclass">
我只想填写第一个输入框。
如果它有一个 ID,我就可以 document.getElementById
...
class 和类型被网站上的几个输入字段使用。我能以某种方式使用占位符吗?
只需 select 它与 document.querySelector('input.someclass')
编辑
如果您网站上输入的顺序和数量始终相同,请执行以下操作:
const inputs = document.querySelectorAll('input')
您可以从 querySelectorAll returns 的数组中选择输入,或者循环遍历数组来输入值。
const inputs = document.querySelectorAll('input');
const valuesToInput = [1,2,3,4,5,6,7,8,9];
for(let i = 0; i < inputs.length; i += 1) {
inputs[i].value = valuesToInput[i];
}
如果您为表单和输入添加 属性 "name",您可以通过以下方式使用它:
<form name="myForm">
<input type="text" name="myText">
<button onclick="addText(myForm)">Add Text</button>
</form>
在javascript中:
function addText(myForm){
myForm.myText.value = 'some text';
}