我正在尝试在javascript中编写一个函数,它会自动将一个按钮添加到某些来自特定类的组件中。
我最后成功编写了以下代码:
<html>
<head>
<script type="text/javascript">
window.onload=function populateEditContainer(){
//function populateEditContainer(){
console.log("fonction");
var editContainers = document.getElementsByClassName("editContainer");
console.log("collection");
console.log(editContainers);
console.log("taille");
console.log(editContainers.length);
console.log(editContainers);
for(var i=0, editContainer; editContainer = editContainers[i]; i++){
console.log("boucle");
console.log(editContainer);
var form = document.createElement("form");
console.log(form);
form.setAttribute('method',"post");
console.log(form);
var button = document.createElement("input");
console.log("trace");
button.setAttribute('type',"button");
button.setAttribute('value',"editer");
console.log(button);
form.appendChild(button);
editContainer.appendChild(form);
}
}
console.log("code");
//window.onload=populateEditContainer();
</script>
<title>Configurations</title>
</head>
<body>
<h1>
Configuration manager !
</h1>
<P>Current configuration</P>
<div style="width:33%">
<table style="width:100%">
<tr>
<td>header reference label</td>
<td></td>
<td class="editContainer" />
</td>
</tr>
<tr>
<td>highlight color</td>
<td></td>
<td class="editContainer" />
</tr>
<tr>
<td>account number</td>
<td></td>
<td class="editContainer" />
</tr>
</table>
</div>
</body>
但是,在此之前,我遇到了一个我无法理解的问题。
问题:HTMLCollection.length保持零作为值,但是集合似乎在调试视图中正确填充,因此根本不执行循环。
<html>
<head>
<script type="text/javascript">
//window.onload=function populateEditContainer(){
function populateEditContainer(){
console.log("fonction");
var editContainers = document.getElementsByClassName("editContainer");
console.log("collection");
console.log(editContainers);
console.log("taille");
console.log(editContainers.length);
console.log(editContainers);
for(var i=0, editContainer; editContainer = editContainers[i]; i++){
console.log("boucle");
console.log(editContainer);
var form = document.createElement("form");
console.log(form);
form.setAttribute('method',"post");
console.log(form);
var button = document.createElement("input");
console.log("trace");
button.setAttribute('type',"button");
button.setAttribute('value',"editer");
console.log(button);
form.appendChild(button);
editContainer.appendChild(form);
}
}
console.log("code");
window.onload=populateEditContainer();
</script>
<title>Configurations</title>
</head>
<body>
<h1>
Configuration manager !
</h1>
<P>Current configuration</P>
<div style="width:33%">
<table style="width:100%">
<tr>
<td>header reference label</td>
<td></td>
<td class="editContainer" />
</tr>
<tr>
<td>highlight color</td>
<td></td>
<td class="editContainer" />
</tr>
<tr>
<td>account number</td>
<td></td>
<td class="editContainer" />
</tr>
</table>
</div>
</body>
是否可以对此进行解释?
答案 0 :(得分:0)
你有一个错字:
window.onload=populateEditContainer();
此行实际执行您的功能,同步。
您只想传递一个引用以便稍后执行,在线加载:
window.onload=populateEditContainer;
它在顶部示例中起作用的原因是您定义并传递函数,但不执行它。