我正在使用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>
答案 0 :(得分: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));