简体   繁体   English

使用jQuery选择所有目标没有后缀的链接

[英]Choose all links whose targets don't have suffixes using jQuery

How could I perform the selection desribed in the title? 如何执行标题中描述的选择? I think it should be fairly safe to assume that such links don't have anything like .asdafasdfsaf , .html or .zip at the end of their targets, so I tried the following: 我认为假定此类链接在目标末尾没有.asdafasdfsaf.html.zip是相当安全的,因此我尝试了以下操作:

var links = jQuery("a:not([href$='.*'])") // Period as is
var links = jQuery("a:not([href$='\.*'])") // One escape
var links = jQuery("a:not([href$='\\.*'])") // Two escapes

None of these seem to really do anything in terms of preventing the non-desired links from being selected, however. 但是,在阻止选择不需要的链接方面,这些方法似乎都没有任何作用。 How could one fix this? 如何解决这个问题?

EDIT: 编辑:

This attempt with RegExes didn't work: 使用RegExes的尝试不起作用:

function has_suffix (target_string) {
   regex = RegExp("(\/.*\..*)$");
   if ( regex.test(target_string) ) {
     return true;
   } else {
     return false;
   }

var links = jQuery("a").filter(
  function () {
    target = $(this).attr("href")
    console.log(target)
    return $(true,this) === has_suffix(target);
  });

Testing the RegExp in the console seems to do produce the results that I want, but actually utilizing the has_suffix function in the filter is giving me a headache. 在控制台中测试RegExp似乎确实产生了我想要的结果,但是实际上在过滤器中利用has_suffix函数让我头疼。 The documentation for filter is of no use to me; filter的文档对我没有用。 it's not clear enough in its examples. 在示例中还不够清楚。

You can simply return the result of has_suffix() directly, as the filter function already runs once for every element that is matched: 您可以直接直接返回has_suffix()的结果,因为filter函数已经为每个匹配的元素运行一次:

var links = jQuery("a").filter(
  function () {
    target = $(this).attr("href")
    console.log(target)
    return has_suffix(target);
  });

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

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