[英]Assign href of anchor tag
I want to assign href of Anchor tag using JavaScript. 我想使用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>
Change you code to this, 将您的代码更改为此,
<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>
In the code we are assigning the output of your server-side code to a JavaScript variable 'flag' and according to its value JavaScript code will assign the href attribute. 在代码中,我们将服务器端代码的输出分配给JavaScript变量“ flag”,并且根据其值,JavaScript代码将分配href属性。
And we have placed this code in to a JavaScript function, we will call it when document loads, so that it will change ' href
' of anchor properly otherwise the code couldn't access anchor tag before it loads. 并将此代码放入JavaScript函数中,我们将在文档加载时调用它,以便它将正确更改锚的'
href
',否则代码在加载之前无法访问锚标记。
Call the function in body
tag like this, 像这样在
body
标签中调用函数,
<body onload="setHref();">
Hope it works, let me know if you want more help. 希望它能起作用,如果您需要更多帮助,请告诉我。 Thank you.
谢谢。
<a href="Index/MasterPage?modID=<%=Session["ProductID"]%> ">
可以像这样直接使用,我们可以将会话值分配给href
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.