changing img src with JQuery but leave pathing info intact?
I'm using JQuery to switch out an image src thusly:
$("#myImg").attr("src", "../../new.gif");
notice the relative pathing on the new src. Unfortunately, this isn't portable when I deploy my app. In my MVC app I'm using a ResolveUrl() method that will fix the pathing problem for me so it's portable, but now my JQuery image src swapper doesn't work right since it now switches the correctly resolved path to a broken relative one.
<img id="myImg" src="开发者_开发知识库<%=ResolveUrl("~/Images/transparent.gif")%>" />
What I want is for JQuery to just flip the actual filename and leave the path untouched. My first thought would be to
// pseudocode javascript jquery on my thought on how to approach this prob
var oldFullPath = $('#myImg").GetTheImgSrc;
var newFileNameWithPathIntact = someRegexAddNewFileNameWithOldPath
$("#myImg").attr("src", newFileNameWithPathIntact);
but that seems rather gross and un-JQuery to me. Anyone got a better way?
you could use something like this:
var oldImage =$("#myImg").attr("src");
var imagePath = oldImage.slice(0, oldImage.lastIndexOf("/")) + "/new.gif";
$("#myImg").attr("src", imagePath );
EDIT: better code...:)
You can use the resolveurl right in the javascript:
$("#myImg").attr("src", "<%=ResolveUrl("~/Images/new.gif")%>");
That of course assumes that you've included the javascript right in the view. If you have a requirement that this script must live in a separate script file from the html request, then you can just have a view which is a javascript file ... and just reference that URL in the script src:
<script language="javascript" src="<%= Url.Action("MyMethod") %>" />
why not just use a variable for the root of the app that you can use for these types of situations.
var root = "<%=ResolveUrl("~/") %>";
Now you can easily construct your image path
$("#myImg").attr("src", root + "images/" + fileName);
精彩评论