我想使用JavaScript分配Anchor标签的href。
<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="AnchorTRY.aspx.cs" Inherits="AnchorTRY" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<a id="anchr" runat="server"> </a>
<script type="text/javascript">
if (System.Web.HttpContext.Current.Session["Email"] == null && System.Web.HttpContext.Current.Session["uid"] == null)
{
document.getElementById("anchr").setAttribute('href', "User Login.aspx");
document.getElementById("anchr").innerText = "Create Your Own Package";
}
else {
document.getElementById("anchr").setAttribute('href', "Cities.aspx");
document.getElementById("anchr").innerText = "Add to Your Package";
}
</script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder2" Runat="Server">
</asp:Content>
答案 0 :(得分:1)
将您的代码更改为此
<script type="text/javascript">
function setHref() {
var flag = <%
if (System.Web.HttpContext.Current.Session["Email"] == null && System.Web.HttpContext.Current.Session["uid"] == null)
{
response.write("true");
}
else
{
response.write("false");
}
%>;
if(flag == true)
{
document.getElementById("anchr").setAttribute('href', "User Login.aspx");
document.getElementById("anchr").innerText = "Create Your Own Package";
}
else {
document.getElementById("anchr").setAttribute('href', "Cities.aspx");
document.getElementById("anchr").innerText = "Add to Your Package";
}
}
</script>
在代码中,我们将服务器端代码的输出分配给JavaScript变量&#39;标记&#39;并根据其值,JavaScript代码将分配href属性。
我们已将此代码放入JavaScript函数中,我们将在文档加载时调用它,以便它会更改&#39; href
&#39;正确锚定,否则代码在加载之前无法访问锚标记。
在body
标签中调用此功能,
<body onload="setHref();">
希望它有效,如果您需要更多帮助,请告诉我。谢谢。
答案 1 :(得分:1)
<a href="Index/MasterPage?modID=<%=Session["ProductID"]%> ">
可以直接使用,我们可以将会话值分配给href