如何检查href属性是否包含字符串?

时间:2020-04-24 14:05:00

标签: javascript html jquery anchor

我想从页面获取所有“ a”标签,获取其“ href”属性,并检查此href中是否为文本“ .pdf”。因此,我将所有a标记放入tags变量中,然后使用each()函数检查每个“ a”(作为tag)。但是代码:

  if ($(tag).indexOf('.pdf') > 0) 
    console.log($(tag));

不起作用。为什么?为什么我不能在indexOf上使用href?我尝试使用search()函数,但也无法正常工作。

所以我想-好的,href出了点问题。让我们将其作为文本。

但是代码:

  var text = $(tag).text();
    console.log(text);

也不起作用。谁能告诉我为什么?

代码段故意存在错误-表示我有问题。

谢谢。

(function($){
  var tags = $('a');
  $(tags).each(function() {
        var tag = $(this).attr('href')     
        
        if ($(tag).indexOf('.pdf') > 0) 
          console.log($(tag));
            
        var text = $(tag).text();
        console.log(text);
  });
}(jQuery));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<html>
  <a href="https://www.test.com/example.pdf" target="_blank">Link with ".pdf"</a>
  <a href="https://www.test.com/" target="_blank">Link without ".pdf"</a>
</html>

1 个答案:

答案 0 :(得分:3)

在调用indexOf时不需要额外的$(tag)。此时的tag是一个字符串,您无需使其成为jQuery对象。只需致电tag.indexOf('.pdf') > 0。对于字符串,您还可以使用tag.includes('.pdf')或使用tag.substr(tag.length - 4, 4) === '.pdf'使其更加精确。

相关问题