在html中为JavaScript传递变量是一个关键步骤,而后就能够经过对JavaScript变量操做,实现想要达到的目的javascript
本节代码主要使用了JavaScript中的document对象中的getElement方法和HTML元素的value属性html
01.html <!DOCTYPE html> <html> <head> <title>在HTML转换为JavaScript传递变量</title> <body> <script type="text/javascript"> var foobar;//声明全局变量fooabr function pass2var() { foobar = document.getElementById('textfield').value; //获得id为textfield的HTML元素的值 alert('传递变量成功'); }; function displayVar() { alert('变量值为:' + foobar);//显示全局变量foobar } </script> </head> <body> <center> <h1>在HTML转换为JavaScript传递变量</h1> <hr> <br> <h5>单机响应按钮……</h5> <form name="form1" method="post" action=""> <label> <input type="text" name="textfield" id="textfield"> </label> <label> <!-- 绑定onclick单机事件 --> <input type="button" name="button" id="button" value="传递变量" onclick="javascript:void pass2var();"> </label> <label> <!-- 绑定onclick事件 --> <input type="button" name="button2" id="button2" value="显示变量" onclick="javascript:void displayVar();"> </label> </form> </center> </body> </html>