I have some jQuery that writes some image tags t开发者_运维问答o the browser, but I want to reference them such that I don't have to hardcode the path, and I'm not able to use relative paths either. This is a .NET application, and I am trying to use server side tags.
So, I changed the following:
$('#IMG_' + myID).attr('src','../images/plus.gif');
to:
$('#IMG_' + myID).attr('src','<%= Url.Content("~/images/plus.gif") %>');
or:
$('#IMG_' + myID).attr('src','<%= ResolveUrl("~/images/plus.gif") %>');
When it runs I get javascript errors, Invalid argument on line 48, char 325 of jquery-1.4.2.min.js.
Here's something I've done in a couple projects. It's designed to be used with ASP.NET MVC, but I imagine it could be adopted to use with WebForms as well.
script: common.js
function Environment() { }
Environment.vroot = '';
Environment.getUrl = function(path) {
return Environment.vroot + path;
};
partial view/user control: CommonScript.ascx
<script type="text/javascript">
Environment.vroot = '<%= Url.Content("~/") %>';
</script>
I just put CommonScript.ascx on my master page, but you can put it wherever you want. It needs to be rendered after the script reference to common.js though.
If you use this, you can just do this to set your image url:
$('#IMG_' + myID).attr('src', Environment.getUrl('images/plus.gif'));
If you're not using virtual directories on any environment you could just use /images/plus.gif
If your site has an url like this localhost/mysite/default.aspx
it won't work
精彩评论