c# - 如何将波浪号的相对路径呈现为 ../../jquery/javascript 中的相对路径?

标签 c# javascript jquery asp.net html

好吧,我知道我的标题有点令人困惑。我将在下面通过示例明确说明。

<asp:ImageButton ID="imgButton" NavigateUrl="~/Presentation/Resources/Images/addFile.png" runat="server" />

在html中,上面的控件将呈现为

<input type="image" name="imgButton" id="imgButton" src="../../Resources/Images/addFile.png" style="border-width:0px;">

我注意到,它会将 src 从“~”转换为“../../”。它会自动将其排列到文件级别。

所以在 javascript 中,我想用这个 url 设置它的控件:

~/Presentation/Resources/Images/PDF.png

不幸的是,在 html 中它将呈现为

<input type="image" name="imgButton" id="imgButton" src="~/Presentation/Resources/Images/addFile.png" style="border-width:0px;">

我的问题是,如果我想获得带有“~”的“../../”相对路径,我应该怎么写? 我已经试过了,但我无法得到它。

<script type="javascript">
document.getElementById("<%= imgButton.ClientID %>").src = 
"~/Presentation/Resources/Images/PDF.png";
</script>

最佳答案

试试这个:http://weblogs.asp.net/joelvarty/archive/2009/07/17/resolveurl-in-javascript.aspx

In the master page for the site, put this:

<script type="text/javascript">
        var baseUrl = "<%= ResolveUrl("~/") %>";
</script>

Then, in your javascript file, put this function:

function ResolveUrl(url) {
    if (url.indexOf("~/") == 0) {
        url = baseUrl + url.substring(2);
    }
    return url;
}

You could have put the function right in the master page, but then you wouldn’t get intelli-sense on it for the rest of your code. Now you can call ResolveUrl with ~/ right from javascript.

为什么在客户端需要这个?使用 servercontrols(runat=server),您可以使用波浪号解析服务器上的 URL。

关于c# - 如何将波浪号的相对路径呈现为 ../../jquery/javascript 中的相对路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7397939/

相关文章:

c# - 通过代码向hadoop作业提供输入

javascript - 渲染对象数组 React

javascript - 当我点击两次时,css3 转换不起作用

javascript - 来自多个表、多行、同一页的值

javascript - 如何使用JS抓取页面并将变量推送到GTM数据层

后台 worker 中的 C# ProgressBar 数据绑定(bind)

c# - 如何在业务类中注入(inject)IDistributedCache

javascript - 如何用更少的行编写以下代码

jquery - 防止 bootstrap 崩溃动画高于 md 断点

c# - .NET 实体属性作为枚举或对象