开发者

How to show linked file size and type in title attributes using jQuery?

For example:

Before

<a 
target="_blank" 
href="http://www.adobe.com/devnet/acrobat/pdfs/reader_overview.pdf">
Adobe Reader JavaScript specification 
</a>

Because the file is PDF the title should be title="PDF, 93KB, opens in a new window"

<a
title="PDF, 93KB, opens in a new window" 
target="开发者_C百科_blank" 
href="http://www.adobe.com/devnet/acrobat/pdfs/reader_overview.pdf" >
Adobe Reader JavaScript specification
</a>


Like duirlai said, take a look at Find size of file behind download link with jQuery.

Then the way you update your title with jQuery is like this...

$(function() {
  $("a[href$='.pdf']").each(function(i, obj) {
    var link = $(obj);
    $.ajax({
      type: "HEAD",
      url: link.attr("href"),
      success: function() {
        var length = request.getResponseHeader("Content-Length");
        if (!isNaN(parseInt(length))) {
          var fileSize = readablizeBytes(length);
          link.attr("title", "PDF, "+ fileSize  +", opens in a new window");
        }
      }
    })
  })
});

// From http://web.elctech.com/2009/01/06/convert-filesize-bytes-to-readable-string-in-javascript/
function readablizeBytes(bytes) {
  var s = ['bytes', 'kb', 'MB', 'GB', 'TB', 'PB'];
  var e = Math.floor(Math.log(bytes)/Math.log(1024));
  return (bytes/Math.pow(1024, Math.floor(e))).toFixed(2)+" "+s[e];
}


Take a look at this, Find size of file behind download link with jQuery

From that post you can do something like:

<a title="PDF, 93KB, opens in a new window"  target="_blank"  href="http://www.adobe.com/devnet/acrobat/pdfs/reader_overview.pdf"
> Adobe Reader JavaScript specification </a>

$('a').each(function() {
  var request;
  request = $.ajax({
    type: "HEAD",
    url: $("#url").val(),
    success: function () {
      $(this).attr('title', request.getResponseHeader("Content-Length"));
    }
  });
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜