好吧,我知道我的标题有点令人困惑。我将在下面通过示例明确说明。
<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/