向 button 元素分配 onclick 事件:
<!DOCTYPE html> <html> <body> <p>点击按钮就可以执行 <em>displayDate()</em>函数。</p> <button onclick = "displayDate()">点击点击点击</button> <script> function displayDate() { document.getElementById("demo").innerHTML = Date(); } </script> <p id = "demo">会展示日期</p> </body> </html>
2.
<!DOCTYPE html> <html> <body onload = "checkCookies()"> <script> function checkCookies() { try { if (navigator.cookieEnabled == true) { alert("已启用 cookie") } else { alert("未启用 cookie") } } catch (err) { alert('asdf') } } </script> <p>提示框会告诉你,浏览器是否已启用 cookie。</p> </body> </html>
3.
<!DOCTYPE html> <html> <head> <script> function myF() { var x = document.getElementById("fname"); x.value = x.value.toUpperCase(); } </script> </head> <body> 请输入应为字符:<input type = "text" id = "fname" onchange = "myF()"> <p>当您离开输入字段时,会触发将输入文本转换为大写的函数。</p> </body> </html>