오늘자 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>
영삼넷
Categories
Recent Posts
Recent Comments
Statistics
- Total Visitors:
- 372816
- Today:
- 684798
- Yesterday:
- 9751647
IT강국 김영삼 블로그에 오신걸 진심으로 환영합니다.
©2002 영삼넷 // openkr
©2002 영삼넷 // openkr