setting asp hyperlink values JS
i have an asp hyperlink. and i want to set the innerHTML and outerText of this hyperlink in javascript. how can i achieve this?
i have the following code:var path='c:\folder\file.gif'
var H开发者_开发技巧yperlinkObj = GetElementById('hl');
HyperlinkObj.innerHTML ='<a href='+path+'></a>'; //causes: htmlfile: Unknown runtime error
HyperlinkObj.outerText = 'file.gif'; //how can i get the file name from the path?
EDIT:
The following example shows how you can set the properties of an ASP.NET HyperLink
control from javascript.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript">
function setHyperlink(path) {
var link = document.getElementById("<%= myLink.ClientID %>");
link.href = path;
link.innerHTML = getFilenameFromPath(path);
}
function getFilenameFromPath(path) {
return path.replace(/^.*\\/, '');
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
Link: <asp:HyperLink id="myLink" runat="server"></asp:HyperLink><br />
<input type="button" value="Set Hyperlink" onclick="setHyperlink('c:\\folder\\file.gif')" />
</div>
</form>
</body>
</html>
The getFilenameFromPath
function comes from the answer to this question.
ORIGINAL ANSWER:
To setup a hyperlink control from the codebehind, you want to make your hyperlink a server control. Assuming you are working in MyPage.aspx, in the front page you would add the following:
<asp:HyperLink id="myLink" runat="server"></asp:HyperLink>
Then, in the codebehind, say in Page_Load:
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
SetupLink("myfilename.txt");
}
private void SetupLink(string filename)
{
myLink.Text = filename;
//Assumes the file is in the root of your web site
myLink.NavigateUrl = string.Concat("~/", filename);
}
When you add the runat="Server"
tag to the hyperlink, the designer should add the reference for this control in the MyPage.aspx.designer.cs
file. It should look something like this:
protected global::System.Web.UI.WebControls.HyperLink myLink;
After you have that set up, if you need to access the hyperlink control from Javascript, you can use the ClientID
property of the myLink control.
<script type="text/javascript">
var link = document.getElementById("<%= myLink.ClientID %>");
alert(link);
</script>
Hope that helps.
精彩评论