I've got a site where I'd like to have a specific header image displayed for each individual page. The way the layout is done, it's not easily achievable with the current templating system. What I'd like to do is grab the last piece of the url string, create a v开发者_StackOverflow中文版ariable and use that variable to complete an image path. That way I can upload images with the same name and get my desired affect.
I can create the array:
var pathArray = window.location.pathname.split( '/' );
Not sure how to grab the last item. The number of items in the array will vary. Also, not sure exactly how to append the image path. What I need is something like this:
<img src="/headerImages/[variable here].jpg"/>
All the urls on the site do not have .html or .htm so we shouldn't need to filter those out.
Thanks in advance for any help!
By using lastIndexOf()
you can achieve it. The following function extracts the file name from a path array. If the path is in the form "/some/path/fileName.ext" it will return "fileName.ext"; otherwise it returns the argument.
function fileName(pathArray) {
if (pathArray == null)
return null;
var iSlash = pathArray.lastIndexOf('/');
if (iSlash == -1)
return pathArray;
return pathArray.substr(iSlash + 1);
}
You can get the last item of the array by using
pathArray[pathArray.length - 1]
You can get the last element of the array by:
var last = pathArray[pathArray.length - 1];
Add this code at the header image location in you html file:
<script type="text/javascript">
var pathArray = window.location.pathname.split( '/' );
var headerImage = pathArray[pathArray.length - 1];
document.write('<img src="/headerImages/' + headerImage + '.jpg"/>');
</script>
You can use
javascript
var pathArray = window.location.pathname.split( '/' );
var name = pathArray[pathArray.length-1];
to assign the new path to an existing image (which has an id defined) you can use jquery (if you already use it)
$('#imgID').attr('src','/headerImages/'+name+'.jpg');
or plain javascript
document.getElementById('imgID').src = '/headerImages/'+name+'.jpg';
assumed html
<img id="imgID" src="initial_image_path/someimage.jpg" />
精彩评论