jQuery: Display file sizes next to download links
- // Loop all links on page with class .getSize
- $('a.getSize').each(function(){
- // Issue an AJAX HEAD request for each one
- var link = this;
- $.ajax({
- type: 'HEAD',
- url: link.href,
- complete: function(xhr){
- var size = humanization(xhr.getResponseHeader('Content-Length'));
- // Append the filesize to each
- $(link).append(' (' + type + ')');
- }
- });
- });
- function humanization(size){
- var units = ['bytes','KB','MB','GB','TB','PB'];
- var ord = Math.floor( Math.log(size) / Math.log(1024) );
- ord = Math.min( Math.max(0,ord), units.length-1);
- var s = Math.round((size / Math.pow(1024,ord))*100)/100;
- return s + ' ' + units[ord];
- }
- // example html
- // <a href="one.html" class="getSize">Some link</a>
- // <a href="other.html" class="getSize">Other link</a>
- // <a href="car.jpg" class="getSize">Image</a>
Комментариев нет:
Отправить комментарий