【问题标题】:Conditioning in jQuery selectorsjQuery 选择器中的条件
【发布时间】:2013-12-24 17:52:16
【问题描述】:

我对 jQuery 完全陌生,我正在尝试编写一个简单的脚本来说明我想将一个 pdf.png 图像添加到所有以 .pdf 结尾的链接以及一个以 http 开头的外部链接但我对于不同主机上的 PDF 文件,我希望脚本只添加 pdf 图像(我有一个用于添加图像的 css 文件),如下所示:

$(document).ready(function(){
    $("a[href$='.pdf']").addClass('pdf');
    $("a[href^='http']a[href$!='.pdf']").addClass('external');   
});

但当路径以 http 开头并以 .pdf 结尾时,它实际上显示了外部图像(所以它做的相反)。谁能帮我解决这个问题?

【问题讨论】:

  • add an pdf.png image to all the links that end with .pdf and also a external link that starts with http but I don't want for PDF files on different hosts,是什么意思
  • 您想将pdf 类添加到目标以pdf 结尾的锚点以及目标以http 开头但不以http 结尾的锚点的外部类

标签: javascript jquery


【解决方案1】:

下面的代码会将pdf 类添加到href.pdf 结尾但nothttp 开头的元素。根据您的评论,您只需将external 类添加到具有href starts with httpnot ends with .pdfelements。请查看注释下方的代码行以满足您的需求。

试试这个,

$(document).ready(function(){
    $("a[href $= '.pdf']").addClass('pdf');
    //$("a[href^='http']a[href$!='.pdf']").addClass('external');   
    $("a[href^='http']").not("a[href $= '.pdf']").addClass('external');   

});

【讨论】:

  • @ali 你能发布你的示例 html 吗?
  • 哦,我明白了。您的解决方案是正确的,但我需要的有点不同。它的工作原理如下: $("a[href$='.pdf']").addClass('pdf'); $("a[href^='http']").not("a[href$='.pdf']").addClass('external');
  • 我能问你点别的吗?我如何知道一个链接是否是 jQuery 中的外部链接?
  • @ali 我希望这会有所帮助,stackoverflow.com/questions/2910946/…
【解决方案2】:

试试这个

$(document).ready(function(){
    $("a[href^='http']").addClass('external'); 
    $("a[href$='.pdf']").removeClass('external').addClass('pdf');  
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-03-17
    • 2014-04-05
    • 2014-07-12
    • 1970-01-01
    • 2011-04-22
    • 2016-03-04
    • 2016-05-18
    • 1970-01-01
    相关资源
    最近更新 更多