新建一个web工程,FirstWeb,在其中新建一个页面:test.jsp
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>test change herf</title> <script type="text/javascript"> function changeHerf() { var a1 = document.getElementById("a1"); a1.setAttribute("href","www.baidu.com"); var a2 = document.getElementById("a2"); a2.setAttribute("href","http://www.baidu.com"); } </script> </head> <body onload="changeHerf()"> <a herf="#" id="a1">点击我看看,不加http://</a> </br> <a herf="#" id="a2">点击我看看,添加http:/</a> </body> </html>
访问该页面,点击a1时,页面跳转到:http://localhost:8888/FirstWeb/www.baidu.com
点击a2时,页面跳转到www.baidu.com
总结:
动态修改a标签的herf属性时,记得在网址前加上http://