问题
How can I iterate through all forms in a document using javascript?
回答1:
The code below will go through an html document, get all forms and do a pop-up alert of the names of each form.
var formsCollection = document.getElementsByTagName("form");
for(var i=0;i<formsCollection.length;i++)
{
alert(formsCollection[i].name);
}
This is just a start to see if you are getting the reult you require. Thereafter, remove the alert and continue to do what you need to.
回答2:
You can use
document.forms
collection
See forms Collection
回答3:
Here's an example using the document.forms instead of getElementsByTagName().
As with the getElementsByTagName() example this goes through all the forms and does a popup alert with the action (instead of name, as it is more likely to be set).
var formsCollection;
var r;
formsCollection=document.forms;
for(r=0;r<formsCollection.length;r++)
{
alert(formsCollection[r].action);
}
This can be condensed down and of course the popup changed to something useful but I have tried to keep it simple.
And for reference here are some links to more info:
- Mozilla Developer Network
- Microsoft
- w3c
- And even w3schools
来源:https://stackoverflow.com/questions/2146348/javascript-html-how-to-iterate-through-all-the-forms-on-a-page