有时候我们会创建这样的一个a标签,它的的href属性根据页面环境来确定。
比如我们得到一个url: http://www.baidu.com/s?wd=hello
但是我们想根据这个url 来动态设置我们自己的一个a标签的属性为 http://www.google.com/search?q=hello
这个时候我们就可以用javascript函数来取得需要的一些参数,动态进行设置了
// selfObject: 需要设置href属性的a标签 function linkToUrl(selfObject) { var url = "http://www.google.com/search?q="; url += window.location.href; selfObject.href = url; }
下面这个是测试用例,直接保存成jsp文件就可以运行了:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>javascript操纵a标签的href属性</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <script type="text/javascript"> function linkToUrl(selfObject) { var url = "http://www.google.com/search?q="; url += window.location.href; selfObject.href = url; } function showUrl() { var url = "http://www.google.com/search?q="; url += window.location.href; return url; } </script> </head> <body> <div> <a href="javascript:void(0);" onclick="linkToUrl(this)">打开URL页面</a> </div> <div> <a href="javascript:showUrl()">显示URL路径</a> </div> </body> </html>