使用jQuery选择元素子集

时间:2014-11-10 00:05:39

标签: jquery html

下面给出了由链接组成的HTML页面的一部分:

  <ul>
    <li><a href="myPersonalProject.html">myPersonalProject (a local html file)</a></li>
    <li><a href="cv.pdf">my CV (a local PDF file)</a></li>
    <li><a href="archive/2014.zip">archive (a local ZIP file)</a></li>
    <li><a href="http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf">ECMAScript Language Specification (an external PDF)</a></li>
    <li><a href="../pdfs/christmas/">Christmas cards (a local directory with pdf in the pathname - but NOT a pdf file)</a></li>
    <li><a href="https://noppa.tkk.fi/">Noppa (an external link)</a></li>
  </ul>

我需要选择目标以任何结尾(。*)结束的链接,并且不以(.pdf)结尾,同样不以(.html)结尾,并将CSS类应用于它。我需要使用jQuery。我尝试用过滤器来做,但是弄得一团糟,因为我刚开始学习jQuery:

    $("a[href$='.*']").filter(function(){
           $("a[href$!='.pdf']").filter(function(){
                  $("a[href$!='.html']").addClass("download");
            });
     });

我知道这是完全错误的,但我无法弄明白该怎么做。我google了,但filter()内的函数()并不是很清楚。有人可以帮忙吗?

7 个答案:

答案 0 :(得分:2)

您可以将正则表达式与一些简单的测试组合以过滤锚点

$('a').filter(function() {
    var m = this.href.match(/\.(.{3,4})$/), e = m ? m.shift() : null;
    return e && e.indexOf('/') == -1 && e.match(/(pdf|html)/) == null;
}).addClass('download');

FIDDLE

答案 1 :(得分:1)

jQuery属性选择器不允许使用通配符或正则表达式。但是,您不需要使用过滤器来移除.pdf,您可以使用:not选择器:

$("a:not([href$=.pdf]):not([href$=.html])").addClass("download");

当你使用.filter()时,该函数应该返回一个布尔值(表示该元素是否应该包含在结果中),它不应该对元素本身进行操作 - 您对.filter返回的值执行此操作,例如

$(selector).filter(function() {
    return ...;
}).addClass("download");

答案 2 :(得分:1)

您可以使用filter()

$('a')
    .filter(function() {
        //use your required regex to check for link
        return this.href.match(/[^.]*?\.(?!pdf|html)/gi);
    })
    .addClass("download"); //if matched, "download" class is added

答案 3 :(得分:1)

$("a[href]").filter(function (i) {
    var href = $(this).attr("href");
    return (href.indexOf(".pdf") == -1 && href.indexOf(".html") == -1);
})
.addClass("download");

答案 4 :(得分:1)

虽然你说&#34; 需要使用jQuery ,&#34;我想提供一个简单的JavaScript替代方案(将来为自己或他人):

// calls Array.prototype.forEach(), using the array-like NodeList
// returned by document.querySelectorAll(), iterating over that NodeList
[].forEach.call(document.querySelectorAll('li a'), function (aElem) {
    // 'aElem' is the current array-element (the <a>)

    // if the aElem.href property does not (note the '!') end with
    // either 'pdf' or 'html' (RegExp.prototype.test() returns
    // a Boolean)
    if (!(/(pdf|html)$/).test(aElem.href)) {
        // we add the 'download' class to the element:
        aElem.classList.add('download');
    }
});

JS Fiddle link

可替换地:

[].forEach.call(document.querySelectorAll('li a'), function (aElem) {
    // if the final part of the href (following the final '.' character)
    // is not found in the array (and thus an index of -1):
    if (['pdf','html'].indexOf(aElem.href.split('.').pop()) === -1) {
        aElem.classList.add('download');
    }
});

JS Fiddle link

参考文献:

答案 5 :(得分:0)

您还可以执行以下操作:

$("a").each(function( index ) {
    var href = $(this).attr('href');
    if(!((href.toLowerCase().indexOf(".pdf") >= 0) || (href.toLowerCase().indexOf(".html") >= 0))){
        $(this).addClass("download");
    }
});

答案 6 :(得分:0)

我迟到了,对DemoUser的answer

进行了细微的更改

负责URL <#p>中的#anchor

$('a')
    .filter(function() {
        // take care of anchor # in download URL
        return !this.href.match(/\.(pdf|html)(#.*)?$/gi);
    })
    .addClass("download"); //if matched, "download" class is added
相关问题