在HTML中为JavaScript传递变量
在html中为JavaScript传递变量是一个关键步骤,然后就可以通过对JavaScript变量操作,实现想要达到的目的
本节代码主要使用了JavaScript中的document对象中的getElement方法和HTML元素的value属性
- document对象的getElement方法得到HTML元素
- HTML元素的value属性得到HTML元素的value值
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>

浙公网安备 33010602011771号