![](/img/trans.png)
[英]jQuery: extract file name from an href link when adding “download” attribute
[英]What is the best way to cut the file name from 'href' attribute of an 'a' element using jQuery?
例如,我有簡單的代碼:
<ul class="list">
<li><a href="http://www.aaa.com/bbb/ccc/file01.pdf">Download file 01</a></li>
<li><a href="http://www.bbb.com/ccc/ddd/file02.pdf">Download file 02</a></li>
</ul>
並且我只希望在文件中存儲文件名:file01.pdf和file02.pdf,如何剪切它們?
非常感謝您的幫助。
干杯。
采用
給錨標簽一個ID
var elem = document.getElementById ( "anch1" );
elem.href.substring (elem.href.lastIndexOf ( '/' ) + 1 );
使用jQuery
$(function() {
$("ul.list li a").each ( function() {
alert ( $(this).attr ( "href" ).substring ($(this).attr ( "href" ).lastIndexOf ( '/' ) + 1 ) )
});
});
盡管在這種情況下沒有它們,但通常來說,在查找最后一個斜杠以獲取文件的葉名之前,您通常希望剝離?search
和#hash
部分。
使用鏈接對象的內置屬性(例如pathname
)非常簡單,而不是處理完整的href
:
var a= document.getElementById('link1'); // or however you decide to reference it
var filename= a.pathname.split('/').pop(); // get last segment of path
var fileNames = new Array();
$('.list a').each(function(i, item){
fileNames.push(this.href.substring(this.href.lastIndexOf('/') + 1))
});
這將為您提供所有文件名的數組,然后:
for(var x=0; x<fileNames.length; x++)
{
// Do something with fileNames[x]
}
var myFilename = [];
$("ul.list li a").each(function() {
var href = $(this).attr('href');
var idx = $(this).attr('href').lastIndexOf('/');
myFilename.push((idx >= 0) ? href.substring(idx+1) : href);
});
這是另一種方式:
var arr = [];
$("ul.list li a").each (function(){
arr.push( (this.href.match(/\/[^\/]+$/)[0] || '').substr(1) );
});
var files = $('a[href]').map(function() {
return this.pathname.match(/[^\/]*$/)[0];
});
a[href]
將排除沒有a[href]
錨(例如命名錨),而pathname
名將刪除查詢字符串和片段( ?query = string和#fragment )。
之后, files
將包含文件名數組: ['file01.pdf', 'file02.pdf']
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.