javascript: why won't this cause all the forms on a page to reset?

会有一股神秘感。 提交于 2019-12-12 02:15:06

问题


good evening fellow code bashers:

i know it should be simple, but i'm tired and just want to get it done. this is how i thought it should be done, which is identical to how this fellow did it, BUT numberOfForms comes up ZERO, instead of THREE (that's how many forms are on the page, all named & id'd). what did i miss?

var numberOfForms = document.getElementsByTagName("form");
console.log("numberOfForms: " + numberOfForms);
for (var i=0; i<numberOfForms.length; i++)
{
  document.forms[i].reset;
}

shed some light, plz. then i can punch out and hit the hay.


回答1:


Try this. You have already got an array with all HTML DOM Form elements. Use numberOfForms[i].reset() instead of trying to use document.forms[n].

var numberOfForms = document.getElementsByTagName("form"); 
console.log("numberOfForms: " + numberOfForms); 
for (var i=0; i<numberOfForms.length; i++) 
{ 
   numberOfForms[i].reset();
} 

Actually this is cleaner and more efficient, there is actually no need to traverse the DOM with document.getElementsByTagName()

var allForms = document.forms;
for (var i=0; i < allForms.length; i++) {
  allForms[i].reset();
}



回答2:


Try using reset()

var numberOfForms = document.getElementsByTagName("form");
console.log("numberOfForms: " + numberOfForms);
for (var i=0; i<numberOfForms.length; i++)
{
  document.forms[i].reset();
}


来源:https://stackoverflow.com/questions/7801749/javascript-why-wont-this-cause-all-the-forms-on-a-page-to-reset

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!