【发布时间】:2011-07-15 12:48:26
【问题描述】:
您好,我有这个 javascript,当用户单击按钮时会添加一个文本框。然后将文本框添加到 DOM 网页中。
但是它现在似乎并没有停止并陷入无限循环。
循环使用
GetElementsbyTagName
以及有多少限制,但它在早些时候运行良好。
//add rows function
window.onload=function()
{
s=5; //for staff
n=20; //for events
//sets at default incase no js rows created
var staffbox = document.getElementById('staffcounter');
staffbox.value = s;
var eventsbox = document.getElementById('eventscounter');
eventsbox.value = n;
inp=document.getElementsByTagName('input');
for(c=0;c<inp.length;c++) // <---- I think this bit is causing the crash!
{
if(inp[c].name=='addstaff')
{
inp[c].onclick=function()
{
var sel = document.createElement('select');
sel.name = 'staff' + s;
option1 = document.createElement('option');
option1.name = 'Please select';
option1.value = '';
option1.innerHTML = option1.value;
option2 = document.createElement('option');
option2.name = 'Nurse';
option2.value = 'Nurse';
option2.innerHTML = option2.value;
sel.appendChild(option1);
sel.appendChild(option2);
document.getElementById('staffarea').appendChild(sel);
x=document.createElement('input');
x.setAttribute('rows',1);
x.setAttribute('cols',20);
x.name='staffquantity'+s;
document.getElementById('staffarea').appendChild(x)
document.getElementById ('staffarea').innerHTML += '<br>';
// This bit updates a counter that will be $_POST
var staffbox = document.getElementById('staffcounter');
staffbox.value = s;
s++;
}
}
else if(inp[c].name=='addevent')
{
timemaker(); // calls another function which creates a specific text box
x=document.createElement('input');
x.setAttribute('rows',1);
x.setAttribute('cols',20);
x.name='event'+n;
document.getElementById('eventarea').appendChild(x);
x=document.createElement('input');
x.setAttribute('rows',1);
x.setAttribute('cols',20);
x.name='supplies'+n;
document.getElementById('eventarea').appendChild(x);
x=document.createElement('input');
x.setAttribute('rows',1);
x.setAttribute('cols',20);
x.name='manufacturer'+n;
document.getElementById('eventarea').appendChild(x);
x=document.createElement('input');
x.setAttribute('rows',1);
x.setAttribute('cols',20);
x.name='quantity'+n;
document.getElementById('eventarea').appendChild(x);
var sel = document.createElement('select');
sel.name = 'success' + n;
y = document.createElement('option');
y.name = 'Yes';
y.value = 'Yes';
y.innerHTML = y.value;
x = document.createElement('option');
x.name = 'No';
x.value = 'No';
x.innerHTML = x.value;
sel.appendChild(y);
sel.appendChild(x);
document.getElementById('eventarea').appendChild(sel);
x=document.createElement('input');
x.setAttribute('rows',1);
x.setAttribute('cols',20);
x.name='comment'+n;
document.getElementById('eventarea').appendChild(x);
document.getElementById ('eventarea').innerHTML += '<br>';
// This bit updates a counter that will be $_POST
var eventsbox = document.getElementById('eventscounter');
eventsbox.value = n;
n++;
}
}
return;
}
谢谢
【问题讨论】:
-
您是否有任何理由不按 ID 检索输入?在这种情况下,您不需要循环。
-
我不知道,我只是修改了一个示例代码,只是添加了一个文本框,
标签: javascript jquery html crash