오늘자 ajaxian에 올라온 포스트 중에 jQuery Tip으로 링크에 걸린 파일사이즈를 자동으로 알아낸뒤 링크뒤에 출력해주는 포스팅을 번역해서 올려본다.



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 <units.length; i++){

var unitSize = units[i][0];
var unitText = units[i][1];

if (length>= 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);
}
});
});
});


소스에서 굵게 표시된 json.headers 를 이용해서 컨텐츠의 사이즈를 알아온뒤 link.after메쏘드로 화면에 출력해 주었다...
너무도 간단하게.. ㅡ.,ㅡ;

addSizes.js

샘플사이트 : http://natbat.net/code/clientside/js/addSizes/
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">

<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>addSizes</title>
<!-- Date: 2008-07-29 -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js" type="text/javascript"></script>
<script src="addSizes.js" type="text/javascript"></script>
</head>
<body>
<h1>addSizes</h1>
<p>This is a link to a remote <a href="http://clearleft.com/worksheet/client-worksheet.doc">doc</a> file.</p>
<p>This is a link to a remote <a href="http://www.onyx.com/pdf/CustomerMgmtBrochure.pdf">pdf</a> file.</p>
<p>This is a link to a remote <a href="http://media.giantbomb.com/podcast/giantbombcast-071708.mp3">mp3</a> file.</p>

<p>This is a link to a local <a href="media/test.doc">doc</a> file.</p>
<p>This is a link to a remote <a href="media/test.pdf">pdf</a> file.</p>
<p>This is a link to a remote <a href="media/test.mp3">mp3</a> file.</p>
</body>
</html>

'JS > jquery' 카테고리의 다른 글

jQuery 스크롤 페이징  (0) 2012.01.16
스크롤 페이징(Scroll Paging, Continuous scrolling pattern)  (0) 2012.01.16
How to Mimic the iGoogle Interface  (0) 2009.03.01
The 20 Most Practical and Creative Uses of jQuery  (0) 2009.02.27
jQuery Plugin  (0) 2009.02.23
jQuery Loading바 구현하기  (0) 2009.01.05
Test if jquery has loaded  (0) 2009.01.05
IE를 위해 코딩할때  (0) 2009.01.05
CSS Text Gradients  (0) 2009.01.04
jQuery 강좌 링크  (0) 2008.12.14
by Anna 안나 2009. 1. 5. 01:23