3

我有一个超链接,在某些情况下我想更改以显示 jquery 弹出窗口,但是在母版页上执行此操作时遇到了一个奇怪的问题。以下工作在常规页面中:

hyp1.NavigateUrl = "#notificationPopup";

呈现为:

<a id="ctl00_hyp1" href="#notificationPopup">Example</a>

这正是我想要的。问题在于它呈现为的母版页上的超链接上的代码完全相同:

<a id="ctl00_hyp1" href="../MasterPages/#notificationPopup">Example</a>

当我在母版页上设置它时,它看起来可能正在通过 ResolveClientUrl() 或其他方式运行 navigateUrl。我尝试将<asp:hyperlinka换成<a href runat=server,但同样的事情发生了。

有任何想法吗?

4

4 回答 4

1

Control.ResolveClientUrlMSDN方法描述上有一个注释。

此方法返回的 URL 相对于包含实例化控件的源文件的文件夹。继承此属性的控件(如 UserControl 和 MasterPage)将返回相对于控件的完全限定 URL。

因此,您的示例中母版页的行为是完全可以预测的(尽管使用起来不太舒服)。那么有哪些替代方案呢?

最好的方法是将 设置<a>为客户端控件(删除runat="server");即使在母版页中也应该像魅力一样工作:

<a href="#notificationPopup">Example</a>

如果此控件应仅在服务器端使用:您可以使用UriBuilder类从后面的代码构建一个 URL:

UriBuilder newPath = new UriBuilder(Request.Url);
// this will add a #notificationPopup fragment to the current URL
newPath.Fragment = "notificationPopup";
hyp1.HRef = newPath.Uri.ToString();
于 2011-03-08T14:46:47.220 回答
0

在您的表单上创建一个隐藏字段并将值设置为您要导航的位置/超链接的 url 而不是超链接导航 url。然后在 javascript 中调用超链接的 onclick 方法,并在浏览器进行实际导航之前将超链接设置在那里。

<html><head><title></title></head>
<script type="text/javascript">

function navHyperlink(field)
{
field.href = document.getElementById('ctl00_hdnHypNav').value;
return true;
}

</script>
<input type="hidden" id="hdnHypNav" value="test2.html" runat="server"/>
    <a href="" onclick="navHyperlink(this);" >click here</a>
</html>

后面的代码是: hdnHypNav.value = "#notificationPopup";

您也可以尝试在回发后使用以下代码设置 url,即将您的代码替换为后面的代码,但我不确定它是否会起作用......

ScriptManager.RegisterStartupScript(this,this.GetType(),"SetHyp","$('ctl00_hyp1').href = '#notificationPopup';",True)
于 2011-03-08T11:34:20.617 回答
0

我找到了另一种解决问题的方法。

hyp1.Attributes.Add("href", "#notificationPopup");
于 2016-01-21T02:34:53.080 回答
0

看到我用静态超链接替换静态超链接的全部原因runat="server"是为了从基于资源的自动本地化中受益,但这些答案都没有满足我的需求。

我的解决方法是将超链接括在文字中:

<asp:Literal ID="lit1" runat="server" meta:resourcekey="lit1">
  <a href="#notificationPopup">Example</a>
</asp:Literal>

不利的一面是,如果您需要以编程方式操作链接,那就更烦人了:

lit1.Text = String.Format("<a href=\"{0}\">Example</a>", HttpUtility.HtmlAttributeEncode(url));
于 2022-02-23T15:39:38.350 回答