суббота, 3 августа 2013 г.

jQuery: Display file sizes next to download links

jQuery: Display file sizes next to download links


  1. // Loop all links on page with class .getSize
  2. $('a.getSize').each(function(){
  3. // Issue an AJAX HEAD request for each one
  4. var link = this;
  5. $.ajax({
  6. type: 'HEAD',
  7. url: link.href,
  8. complete: function(xhr){
  9. var size = humanization(xhr.getResponseHeader('Content-Length'));
  10. // Append the filesize to each
  11. $(link).append(' (' + type + ')');
  12. }
  13. });
  14. });
  15. function humanization(size){
  16. var units = ['bytes','KB','MB','GB','TB','PB'];
  17. var ord = Math.floor( Math.log(size) / Math.log(1024) );
  18. ord = Math.min( Math.max(0,ord), units.length-1);
  19. var s = Math.round((size / Math.pow(1024,ord))*100)/100;
  20. return s + ' ' + units[ord];
  21. }
  22. // example html
  23. // <a href="one.html" class="getSize">Some link</a>
  24. // <a href="other.html" class="getSize">Other link</a>
  25. // <a href="car.jpg" class="getSize">Image</a>


Комментариев нет:

Отправить комментарий

Постоянные читатели

Популярные сообщения