第一种方法,通过元素的name获取
使用方法:
document.pref.color.value;//pref表示form表单的name,color是表单中元素的名称。
实例:
<HTML>
<HEAD>
< LANGUAGE=\" \">
function showColor(){
var color = document.pref.color.value;
console.log(\"Your favorite color is: \" + color);
}
</ >
</HEAD>
<BODY>
<FORM NAME=\"pref\" METHOD=POST>
Enter the name of your favorite car:
<INPUT TYPE=\"text\" NAME=\"car\" SIZE=25>
<INPUT id=\"button1\" TYPE=\"BUTTON\" NAME=\"carButton\" VALUE=\"Show Car\" =\"showCar(this.form)\">
<BR>
Enter your favorite color:
<INPUT TYPE=\"text\" NAME=\"color\" SIZE=15>
<INPUT TYPE=\"BUTTON\" NAME=\"colorButton\" VALUE=\"Show Color\" =\"showColor(this.form)\">
</FORM>
</BODY>
</HTML>
上面实例代码使用ocument.pref.color.value获取pref表单中name为color元素的值。
第二种方法:通过元素的index获取
使用方法:
document.pref.elements[0].value //表示name为pref表单中第一个元素的值
实例:
<HTML>
<HEAD>
< LANGUAGE=\" \">
function showCar(){
var car = document.pref.elements[0].value;
console.log(\"Your favorite car is: \" + car);
}
</ >
</HEAD>
<BODY>
<FORM NAME=\"pref\" METHOD=POST>
Enter the name of your favorite car:
<INPUT TYPE=\"text\" NAME=\"car\" SIZE=25>
<INPUT id=\"button1\" TYPE=\"BUTTON\" NAME=\"carButton\" VALUE=\"Show Car\" =\"showCar(this.form)\">
<BR>
Enter your favorite color:
<INPUT TYPE=\"text\" NAME=\"color\" SIZE=15>
<INPUT TYPE=\"BUTTON\" NAME=\"colorButton\" VALUE=\"Show Color\" =\"showColor(this.form)\">
</FORM>
</BODY>
</HTML>
此实例获取了表单中第一个元素的值,表单的第一个元素应该是name为car的input
第三种方法:通过元素的id获取
document.getElementById(\"id\").value;
实例:
<html>
<body>
< language=\" \">
function getName(){
var textName = document.getElementById(\"text_id\").value;
console.log(\"The textbox name is: \" + textName);
}
</ >
<form name=\"form1\">
This is a blank input textbox. Click on the button below to get the name of the textbox.
<br>
<input type=\"text\" id=\"text_id\" name=\"textbox1\" size=25>
<br><br>
<input type=\"button\" value=\"Get Name\" = getName()>
</form>
</body>
</html>
使用document.getElementById("text_id")获取id为text_id的input.
注:本文章的实例代码均可复制到这里运行并查看结果,你不妨试一把。
继续阅读与本文标签相同的文章
上一篇 :
微服务架构下数据一致性最佳实践
下一篇 :
Google搜索算法是如何越来越懂你的?
-
城市数字化后,新一代内生安全系统可全方位保护
2026-05-14栏目: 教程
-
谷歌也来“唱衰”5G,5G手机只会徒增功耗?为何这么说?
2026-05-14栏目: 教程
-
量子信息和量子技术白皮书合肥宣言在中科大发布
2026-05-14栏目: 教程
-
微信悄悄更新一新功能,来看看!
2026-05-14栏目: 教程
-
打破三大运营商垄断,第四大运营商终于来了!
2026-05-14栏目: 教程
