动态指定超链接参数的几种方法
有些环境下我们需要根据页面中JavaScript变量的值来确定某个(某些)超链接的参数,如“http://www.bla.com/test.aspx?var1=”中,究竟var1等于多少,要根据JavaScript变量来判定
方法一:很简单,客户端脚本
<a href="#" onclick="redirectURL();" class="parent">Mark</a>
function redirectURL(){
var jsvar1;
var jsvar2;
window.location="http://www.bla.com/test.aspx?var1="+jsvar1;//jsvar1为JavaScript变量
}
方法二:在服务端Load时赋值 The easiest way would be to add the runat="server" property to the anchor and set the href in the CodeBehind
<a id="yourAnchor" href="#" class="parent" runat="server">Mark</a>
private void Page_Load(object sender, System.EventArgs e)
{
yourAnchor.HRef = redirectURL();
}
private string redirectURL()
{
string jsvar1 = "";
string jsvar2 = "";
return "http://www.bla.com/test.aspx?var1=" + jsvar1;
}
方法三:客户抱怨说页面上这种超链接很多,不适合为每个超链接写一段onclick的Script,想了一下,还有种方法可以使大量动态超链接的管理方便一点:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
<script language="javascript" type="text/javascript">
// <!CDATA[
var jsvar1="222"
function redir(href)
{
document.getElementById("Hidden1").value=(href+jsvar1);
document.getElementById("Button1").click();
}
// ]]>
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<a href="http://www.bla.com/test.aspx?var1=" onclick="redir(this.href); return false;">Mark</a>
</div>
<asp:Button style="display:none" ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
<input id="Hidden1" type="hidden" runat="server" />
</form>
</body>
</html>
protected void Button1_Click(object sender, EventArgs e)
{
ScriptManager.RegisterStartupScript(Page, this.GetType(), "key", "window.location='"+this.Hidden1.Value+"'", true);
}