简体   繁体   English

使用jQuery从“ a”元素的“ href”属性中剪切文件名的最佳方法是什么?

[英]What is the best way to cut the file name from 'href' attribute of an 'a' element using jQuery?

For example I've got the simple code: 例如,我有简单的代码:

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

and I wish to store in variables only the file names: file01.pdf and file02.pdf, how can I cut them? 并且我只希望在文件中存储文件名:file01.pdf和file02.pdf,如何剪切它们?

Many thanks for the help. 非常感谢您的帮助。

Cheers. 干杯。

use 采用

lastIndexof and substring lastIndexof子字符串

Give anchor tag an id 给锚标签一个ID

var elem = document.getElementById ( "anch1" );

elem.href.substring (elem.href.lastIndexOf ( '/' ) + 1 );

Using jQuery 使用jQuery

$(function() {
    $("ul.list li a").each ( function() {
        alert ( $(this).attr ( "href" ).substring ($(this).attr ( "href" ).lastIndexOf ( '/' ) + 1 ) )
    });
});

Though you don't have them in this case, in general you would want to strip off the ?search and #hash parts before looking for the last slash to get the file's leafname. 尽管在这种情况下没有它们,但通常来说,在查找最后一个斜杠以获取文件的叶名之前,您通常希望剥离?search#hash部分。

This is very easy using the built-in properties of the link object like pathname instead of processing the complete href : 使用链接对象的内置属性(例如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))
});

This will give you an array of all the filenames, then: 这将为您提供所有文件名的数组,然后:

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

Here another way: 这是另一种方式:

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] will exclude anchors without hrefs (such as named anchors), and pathname will remove query strings and fragments ( ?query=string and #fragment ). a[href]将排除没有a[href]锚(例如命名锚),而pathname名将删除查询字符串和片段( ?query = string#fragment )。

After this, files will contain an array of filenames: ['file01.pdf', 'file02.pdf'] . 之后, files将包含文件名数组: ['file01.pdf', 'file02.pdf']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM