【问题标题】:jQuery: extract file name from an href link when adding "download" attributejQuery:添加“下载”属性时从href链接中提取文件名
【发布时间】:2020-07-08 16:40:23
【问题描述】:

我正在使用生成的 html,其中包含指向带有 .dxf 后缀的文件的链接:

<a href="http://example.com/filetodownload.dxf">Download File</a>

由于我无法更改动态创建的 html,我使用它来将下载属性添加到这些 href 链接:

jQuery('a[href*=".dxf"]').each(function() {
jQuery("a").attr("download", "downloadedfile.dxf");
});

这会强制浏览器打开“下载并保存”对话框。

问题是我希望下载属性在链接中有文件名,即filetodownload.dxf,而不是jQuery函数中默认的downloadedfile.dxf

如何让 jQuery 使用真实的文件名?我可以调用一个作为实际文件名的变量吗?如何从链接中提取文件名?

我不希望页面上有一个框来命名下载的文件,例如Custom download name with Javascript or JQuery

我无法从浏览器中的 URL 获取文件名,因为该文件是 html 下载链接,而不是 URL,例如 js function to get filename from url

【问题讨论】:

  • ""我无法从 URL 中获取文件名,因为该文件是下载链接,而不是 URL" — 这没有意义。href 属性 必须 是 URL 链接只是您单击以导航到 URL 上的某个内容的内容。
  • 谢谢,我已经澄清了。

标签: javascript html jquery


【解决方案1】:

你可以这样做:

jQuery('a[href*=.dxf]').each(function () {
    $(this).attr("download", this.href.split("/").pop().split("#")[0].split("?")[0]);
});

here 获得拆分器。

【讨论】:

  • 谢谢,但请参阅 amphetamachine 对每个问题的回答。
  • @BlueDogRanch 实际上这也可以。 $(this) 指代该迭代的元素。
【解决方案2】:

.each() 中调用jQuery("a").attr("download", "downloadedfile.dxf"); 会更新所有元素的download 属性多次,而不仅仅是您尝试更新的那个。

您必须将元素传递到您的 .each 回调中,或者使用 $(this) 来继续引用您正在迭代的集合中的“当前”元素。

jQuery('a[href*=".dxf"]').each(function(i, $elem) {
    var pathname;
    if (typeof URL !== 'undefined') {
        var url = new URL($elem.attr('href'));
        // Note: Using URL.pathname strips off the #hash and ?foo=bar arguments
        // e.g. 'https://example.com/foo/bar/baz.xls?id=2&a=b#hash'
        //   -> 'baz.xls'
        pathname = url.pathname.split('/').pop();
    } else {
        // must be IE11 or older (~1.38% user share as of 2020-07-08)
        pathname = $elem.attr('href');
    }
    var filename = pathname.split('/').pop();
    $elem.attr("download", filename);
});

注意:IE 11 或更早版本不支持URL 类。

【讨论】:

  • IE 11 很有趣; kmoser 或 Тимофей 的答案是否支持 IE11 及更早版本?
  • 添加了 IE11 支持。
【解决方案3】:

对于每个<a> 标记,使用正则表达式提取href 属性中的文件名并将download 值设置为:

jQuery('a[href*=".dxf"]').each(function() {
    let url = $(this).attr('href');
    let filename = url.split('/').pop() // https://stackoverflow.com/a/17143667/378779
    console.log(filename);
    $(this).attr("download", filename);
});

【讨论】:

  • 谢谢,但请参阅 amphetamachine 对每个问题的回答。
  • @BlueDogRanch 实际上这很好用,因为他们使用了$(this)
【解决方案4】:

我希望我对您的理解正确,但这应该可以:

jQuery('a[href*=".dxf"]').each(function() {
    jQuery("a").attr("download", jQuery(this).attr('href').split('/').pop());
});

【讨论】:

  • 谢谢,但请参阅 amphetamachine 对每个问题的回答。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-27
  • 2023-03-14
  • 1970-01-01
  • 1970-01-01
  • 2018-01-19
  • 2018-03-02
  • 2021-12-19
相关资源
最近更新 更多