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

I want to get all "a" tags from page, get its "href" attribute and check if in this href is text ".pdf". So I get all a tags into tags variable, then with each() function I check every "a" (as a tag). But code:

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

is not working. Why? Why I can't use indexOf on href? I tried with search() function, but it's also not working.

So I thought - ok, there's something wrong with this href. Lets take it as a text.

但是代码:

  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>
评论
  • gest
    gest 回复

    No need to for the additional $(tag) when calling indexOf. tag is a string at that point and you don't need to make it a jQuery object. simply call tag.indexOf('.pdf') > 0. For strings you can also use tag.includes('.pdf') or you go for tag.substr(tag.length - 4, 4) === '.pdf' to make it even more precise.