关于如何使用JavaScript确定文件类型,我需要帮助。例如,在这个html中。
<div class="indi-download">
<div class="pull-left">
<h6 class="file-format">%file_display_name%</h6>
</div>
<div class="pull-right">
<a class="download-link" href="%file_url%">Download</a>
</div>
在这一行代码中,
<a class="download-link" href="%file_url%">Download</a>href="%file_url%“将返回具有以下扩展名的文件类型:示例:.docx或.pdf。
就像这样。
<a class="download-link" href="http://mysite.com/download/myfiles/sample.pdf">Download</a>我的问题是,我需要检测使用javascript的文件类型。如果是.pdf,class=类的“文件格式”将转换为class=“pdf-文件格式”和class=“doc format”( .doc )。这取决于文件扩展名。知道怎么做吗?做这件事最好的办法是什么?
这是我的示例输出,我只想更改文件的图标,这就是我需要更改类名的原因。

编辑我做了类似的事情,但是如果列表中有多个条目,它就不能工作。它只在第一个项目上工作。请帮帮我。
<body onload="myFunction()">
<div class="indi-download">
<div class="pull-left">
<h6 class="pdf-file" id="file-display-id">%file_display_name%</h6>
</div>
<div class="pull-right">
<a class="download-link" id="download_link" href="%file_url%">Download</a>
</div>
</div>
</body>JavaScript
<head>
<script type="text/javascript">
function myFunction()
{
var url = document.getElementById("download_link").href;
var ext = url.split('.').pop();
if(ext=='pdf'){
var newfileclass = document.getElementById("file-display-id");
newfileclass.className="pdf-file";
}
else if((ext=='docx')){
var newfileclass = document.getElementById("file-display-id");
newfileclass.className="pdf-file doc-file";
}
else if(ext=='zip'){
var newfileclass = document.getElementById("file-display-id");
newfileclass.className="pdf-file zip-file";
}
else{
var newfileclass = document.getElementById("file-display-id");
newfileclass.className="other-file";
}
}
</script>
</head>发布于 2013-10-31 07:31:10
如果您的所有文件都有一个扩展名,只需将文件名与extension = filename.split('.');分开,并根据扩展名确定文件类型。
这个怎么样:
function changeClass(fileUrl){
var extension = fileUrl.split('.').pop();
if(extension.toLowerCase() == 'pdf')
{
return "pdf-file-format";
}
}
$(document).ready(function(){
$(a).live().addClass(changeClass( $(a).attr('href') ) );
});这是一种伪代码,我还没有对它进行测试,但我认为您理解我的想法;)
也如拉克希米所说:How to get a extension of a file using jquery or javascript?
发布于 2013-10-31 07:38:55
课程必须是“pdf-文件格式”吗?我直接通过CSS在我自己的站点上检测到.pdf文件链接,如
a[href$="pdf"] { /* css styles for pdf links */ }嗯?
发布于 2013-10-31 07:40:20
给标签一个id
<a class="download-link" id="download_link" href="http://mysite.com/download/myfiles/sample.pdf">Download</a>并使用此javascript函数更改类。
var change_class_a = function(url) {
var m = url.match(/(.*)[\/\\]([^\/\\]+)\.(\w+)$/);
if(m[3] == 'pdf')
document.getElementById("download_link").className = "YOUR_CLASS";
};
var url = document.getElementById("download_link").href;
change_class_a(url); https://stackoverflow.com/questions/19700441
复制相似问题