---
title: "addSizes.js 自定标注链接文件的大小 "
author: "imhades"
date: "2008-09-03T13:26:21Z"
tags: ["JavaScript", "PHP", "jQuery", "json"]
categories: ["Web前端"]
slug: "addsizes-js"
draft: false
lastmod: "2008-09-03T13:26:21Z"
id: 236099
url: "https://imhades.iteye.com/blog/236099"
---

**来源: [OurJS.cn](http://www.ourjs.cn/) , 原文: [http://www.ourjs.cn/show.php?id=448](http://www.ourjs.cn/show.php?id=448)**

 

 

[addSizes.js](http://natbat.net/2008/Aug/27/addSizes/) 是一段 JS 代码 , 用于从一个页面里链接的一些大的文件 , 并自动在它们的链接旁边标注文件大小。它的作者是 [Nathalie Downe](http://natbat.net/) ，应用了 [Simon Willison](http://simonwillison.net/) 的 [json-head](http://simonwillison.net/2008/Jul/29/jsonhead/) App Engine 迷你服务。

使用它，你的链接不需要额外的代码，它自动会在页面里找到你的链接并更改为这样的格式，如 ” 你的链接 (pdf 2.8 MB)” 。的确很好用！

 

JAVASCRIPT:

 

jQuery( function ($) {

 

    $( 'a\[href$=".pdf"], a\[href$=".doc"], a\[href$=".mp3"], a\[href$=".m4u"]' ).each( function () {

         // looking at the href of the link, if it contains .pdf or .doc or .mp3

         var link = $( this );

         var bits = this .href.split( '.' );

         var type = bits\[bits.length -1];

               

         var url= "http://json-head.appspot.com/?url=" +encodeURI($( this ).attr( 'href' ))+ "&callback=?" ;

 

         // then call the json thing and insert the size back into the link text

         $.getJSON(url, function (json) {

                if (json.ok && json.headers\[ 'Content-Length' ]) {

                        var length = parseInt(json.headers\[ 'Content-Length' ], 10);

 

                        // divide the length into its largest unit

                        var units = [

                              \[1024 * 1024 * 1024, 'GB' ],

                              \[1024 * 1024, 'MB' ],

                              \[1024, 'KB' ],

                              \[1, 'bytes' ]

                         ];

 

                         for ( var i = 0; i &lt;units.length; i++) {

 

                               var unitSize = units\[i]\[0];

                               var unitText = units\[i]\[1];

 

                               if (length&gt;= unitSize) {

                                       length = length / unitSize;

                                       // 1 decimal place

                                       length = Math.ceil(length * 10) / 10;

                                       var lengthUnits = unitText;

                                        break ;

                               }

                         }

                          // insert the text directly after the link and add a class to the link

                         link.after( ' (' + type + ' ' + length + ' ' + lengthUnits + ')' );

                         link.addClass(type);

                     }

           } );

     } );

} );

**来源: [OurJS.cn](http://www.ourjs.cn/) , 原文: [http://www.ourjs.cn/show.php?id=448](http://www.ourjs.cn/show.php?id=448)**