也许这很愚蠢,但我无法理解在函数children
中传输的输入参数有什么问题。
我正在尝试向函数children
发送DOM中元素的ID - table
和ol
,然后在console.log
中输出这些元素。
<body>
<table id="table">
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
</table>
<ol id="ol">
<li>11</li>
<li>22</li>
<li>33</li>
<li>44</li>
</ol>
<script>
function children(elem) {
var idElements = document.getElementById('elem');
console.log(idElements); // result - "null"
}
children(table); // get DOM element with id="table"
children(ol); // get DOM element with id="ol"
</script>
</body>
答案 0 :(得分:4)
function children(elem) {
var idElements = document.getElementById(elem);//remove ("") around elem variable
console.log(idElements);
}
//watch the quotations: send them AS STRINGS
children("table"); // get DOM element with id="table"
children("ol"); // get DOM element with id="ol"
答案 1 :(得分:0)
您当前没有向children函数传递任何内容,因为table和ol都将是未定义的(您将它们作为未定义的变量传递),而是将它们作为字符串传递。此外,从不使用children函数的参数elem
- 它应该传递给getElementById
方法。
function children(elem) {
var idElements = document.getElementById(elem);
console.log(idElements);
}
children('table'); // get DOM element with id="table"
children('ol'); // get DOM element with id="ol"