如何使用jQuery显示链接文件大小和标题属性类型?

时间:2010-03-21 19:59:48

标签: jquery css xhtml accessibility

例如:

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

因为文件是PDF,所以标题应为title="PDF, 93KB, opens in a new window"

<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>

2 个答案:

答案 0 :(得分:1)

看看这个,Find size of file behind download link with jQuery

从那篇文章中你可以做类似的事情:

<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"));
    }
  });
});

答案 1 :(得分:1)

如同杜伊莱所说,请看Find size of file behind download link with jQuery

然后用jQuery更新标题的方式是这样的......

$(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];
}