我正在尝试从用户生成的文本框有序列表中选择输入框的值,并将其值进一步记录到控制台。我无法找到一种方法来选择子元素的值,其中 ID 未知。目前我不断收到此控制台错误:
cannot read property 'getElementsByTagName' of undefined
这是我的 HTML:
<form id="form1" action="processing.php" method="post">
<ol id="spawnList">
</ol>
<button type="button" id="spawnbtn" onClick="spawnSilly();">Add</button>
<button type="button" name="submit" onClick="sub_strings()">Save</button>
</form>
这是用户将生成的一个示例列表元素:
<li id="465817232" class="1" index="1">
<input type="text" placeholder="Title" id="465817232" class="1" index="1">
<button type="button" onclick="redirect()" id="465817232" class="1" index="1">Edit</button>
<button id="465817232" onclick="removeElement(this.id)" class="1" index="1">Delete</button>
</li>
这是我的JS函数:
function sub_strings()
{
var printer = document.getElementById("spawnList").getElementsByTagName["LI"].getElementsByTagName["INPUT"].item[1];
console.log(printer)
}
任何帮助将不胜感激:)
可能你认为元素中的那些属性是数组,但是,这些"属性"是返回"数组"的函数(实际上返回可以被视为数组的对象(。
我建议您使用使用选择器的.querySelector
和/或.querySelectorAll
等函数。
Array.from(document.querySelectorAll('#spawnList li input')).forEach(input => {
console.log(input.id);
});
<form id="form1" action="processing.php" method="post">
<ol id="spawnList">
<li id="465817232" class="1" index="1">
<input type="text" placeholder="Title" id="465817232" class="1" index="1">
<button type="button" onclick="redirect()" id="465817232" class="1" index="1">Edit</button>
<button id="465817232" onclick="removeElement(this.id)" class="1" index="1">Delete</button>
</li>
</ol>
<button type="button" id="spawnbtn" onClick="spawnSilly();">Add</button>
<button type="button" name="submit" onClick="sub_strings()">Save</button>
</form>
您已经阅读了尚未创建的 DOM。li 标签是动态生成的。你应该使用带有 .on (( 的 Jquery 库来实现
$(document).on("click","#spawnList",function() {
// TODO
});