0

我正在使用 jQuery 来计算链接文档的文件大小,使用下面的代码片段。代码在 a 元素之后插入了 span 元素中包装的信息。我想将它插入到 a 元素的值中。这可能吗?

谢谢!

js(来源:http: //jshidell.com/2010/09/20/show-document-file-size-using-jquery/

<script>
  function hdrDetails(i, elm, cl) {
    cl = cl/1024;  //divide content-length by 1024 (KB)
    var sz = cl>1024?"MB":"KB";  //if cl is still big, set to MB
    cl = cl>1024?cl/1024:cl;  //if cl is still big, divide again
    var len = $(elm).eq(i).text().length;  //check the link's text length
    if(len > 0) {
      //add a file size
      $(elm).eq(i).after("<span> ("+cl.toFixed(2)+" "+sz+")</span>");
    }
  }
  $(function() {
    var elm="a[href$='.pdf'],"+ //only the file types we want
    "a[href$='.doc'],"+
    "a[href$='.ppt'],"+
    "a[href$='.xls'],"+
    "a[href$='.docx'],"+ //don't forget 2007 versions
    "a[href$='.pptx'],"+
    "a[href$='.mht'],"+
    "a[href$='.xlsx']";
    $(elm).each(function(i, e) {
      if (e.hostname && e.hostname == location.hostname) {
        $.ajax({
          type: "HEAD",
          url: $(this).attr("href"),
          complete: function(xhr, textStatus) {
          var cl=xhr.getResponseHeader("content-length");
          if(textStatus=="success") {
            var cl=xhr.getResponseHeader("content-length");
            hdrDetails(i, elm, cl); //call the calculation fn
          }else{
            $(elm).eq(i).after("<span> (file not found)</span>");
          }
        }
      });
    }
  });
});
</script>

起始 HTML:

<a href="ms0778.01.01.pdf" target="_blank" title="Anti-Defamation League of B’nai B’rith. 1966,1975.">[Digital Archival Object]</a>

在现有的js之后:

<a href="ms0778.01.01.pdf" target="_blank" title="Anti-Defamation League of B’nai B’rith. 1966,1975.">[Digital Archival Object]</a><span> (1.49 MB)</span>

期望的影响:

<a href="ms0778.01.01.pdf" target="_blank" title="Anti-Defamation League of B’nai B’rith. 1966,1975.">[Digital Archival Object <span>(1.49 MB)</span>]</a>
4

1 回答 1

2

您可以使用它在链接的最后一个字符之前插入文本:

var $e = $(elm).eq(i);
var t = $e.text();
$e.html(t.slice(0, -1)+"<span> ("+cl.toFixed(2)+" "+sz+")</span>"+t.slice(-1));
于 2012-12-13T17:14:02.977 回答