Eg。CCD_ 1将产生一些输入CCD_。
我需要通过id或name="test2"来获得23
索引值var n = document.getElementById('test2').getDOMNodeIndex(); // n = 23
这个解决方案可能有点笨重,但它的工作原理如下所示。
我生成了25个输入元素,并为它们提供了唯一的ID。
然后,我在Form.elements
中选择了一个随机索引,并将其打印到控制台。
然后,我对form.elements
进行迭代,直到找到匹配的.outerHTML
值(JSON.stringified(。当找到匹配时,返回该索引。
const theForm = document.forms[0];
const randomIndex = Math.floor(Math.random() * theForm.elements.length);
console.log(randomIndex);
const theInput = theForm.elements[randomIndex];
const formElementsIndexOf = (form, element) => {
let search = JSON.stringify(element.outerHTML);
for (let i = 0; i < form.elements.length; i++) {
if (JSON.stringify(form.elements[i].outerHTML) === search) {
return i;
}
}
};
console.log(formElementsIndexOf(theForm, theInput));
<form>
<input type="text" id="text0">
<input type="text" id="text1">
<input type="text" id="text2">
<input type="text" id="text3">
<input type="text" id="text4">
<input type="text" id="text5">
<input type="text" id="text6">
<input type="text" id="text7">
<input type="text" id="text8">
<input type="text" id="text9">
<input type="text" id="text10">
<input type="text" id="text11">
<input type="text" id="text12">
<input type="text" id="text13">
<input type="text" id="text14">
<input type="text" id="text15">
<input type="text" id="text16">
<input type="text" id="text17">
<input type="text" id="text18">
<input type="text" id="text19">
<input type="text" id="text20">
<input type="text" id="text21">
<input type="text" id="text22">
<input type="text" id="text23">
<input type="text" id="text24">
</form>