对程序清单 14.2 和14.3 的代码做进一步修改,让没有开启 Javascript 功能的用户只能看到 <noscript> 标签里的内容,看不到额外的文本的按钮。(提示:利用 innerHTML 或 DOM 方法把这些元素写入页面。)
首先列出原代码( html 和 js 文件),再列出解决方法的代码。
原 HTML 代码如下:
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title>Current Date and Time</title> <style type="text/css"> p{ font:14px normal arial,verdana,helvetica; } </style> <script src="datetime(old).js"></script> </head> <body> The current date and time are:<br/> <div id="div1"></div> <input id="btn1" type="button" value="Refresh" /> <noscript> <h1>Your browser dose not support JavaScript.</h1> <p>Please consult your computer's operating system for local date and time information or click <a href="clock.php" target="_blank">HERE</a> to read the server time.</p> </noscript> </body> </html>
原 JS 代码如下:
function telltime(){ var out = ""; var now = new Date(); out += "<br />Date:" + now.getDate(); out += "<br />Month:" + now.getMonth(); out += "<br />Year" + now.getFullYear(); out += "<br />Hours:" + now.getHours(); out += "<br />Minutes:" + now.getMinutes(); out += "<br />Seconds:" + now.getSeconds(); document.getElementById("div1").innerHTML = out; } window.onload = function(){ document.getElementById("btn1").onclick = function(){ location.reload(); } telltime(); }
通过测试并解决方案的代码
新的 HTML 代码如下:(只保留 <noscript> 标签 的内容,并需要为 <noscript> 和 <body> 添加 “id”属性。)
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title>Current Date and Time</title> <style type="text/css"> p{ font:14px normal arial,verdana,helvetica; } </style> <script src="datetime.js"></script> </head> <body id="BODY"> <noscript id="noS"> <h1>Your browser dose not support JavaScript.</h1> <p>Please consult your computer's operating system for local date and time information or click <a href="clock.php" target="_blank">HERE</a> to read the server time.</p> </noscript> </body> </html>
新的 JS 代码如下:
function telltime(){ var out = ""; var now = new Date(); out += "<br />Date:" + now.getDate(); out += "<br />Month:" + now.getMonth(); out += "<br />Year" + now.getFullYear(); out += "<br />Hours:" + now.getHours(); out += "<br />Minutes:" + now.getMinutes(); out += "<br />Seconds:" + now.getSeconds(); var newP = document.createElement("p").appendChild(document.createTextNode("The current date and time are:")); document.getElementById("BODY").innerHTML = newP.textContent + "<br/>" + out + "<br/>"; } window.onload = function(){ var newBtn = document.createElement("input"); newBtn.setAttribute("type","button"); newBtn.setAttribute("value","Refresh"); newBtn.addEventListener('click',function(){location.reload()}); var noScript = document.getElementById("noS"); telltime(); document.body.insertBefore(newBtn,noScript.nextSibling); }
最后,当关闭浏览器的 JavaScript 脚本功能时,只显示 <noscript> 的内容,当开启浏览器的 JavaScript 脚本功能时,修改后的代码与原代码实现效果基本保持一致。