和上次的代碼幾乎一樣,但這次是引用已經寫好的變量。主要功能和用法如下:
- document對象的getElementId方法得到HTML元素。
- HTML元素的value屬性可以用來設置變量的值。
02.html <!DOCTYPE html> <html> <head> <title>在HTML中引用JavaScript的變量</title> <script type="text/javascript"> var foobar = 'foobar';//創建一個全局變量“foobar” function var2pass() { document.getElementById('textfield').value = foobar;//給HTML元素的value屬性賦值 alert('應用變量成功!'); } function displayVar() { alert('變量值為' + foobar); } </script> </head> <body> <h2> 在HTML中引用JavaScript的變量 </h2> <hr> <br> <h5>單機相應的按鈕……</h5> <form name="form1" method="post" action=""> <label> <input type="text" name="textfield" id="textfield"> </label> <!-- 綁定onclick事件 --> <label> <input type="button" name="button" id="button" value="顯示變量" onclick="javascript: void displayVar();"> </label> <!-- 綁定onclick事件 --> <label> <input type="button" name="button2" id="button2" value="引用變量" onclick="javascript: void var2pass();"> </label> </form> </body> </html>