包括如果在jquery中为null

时间:2018-04-08 17:12:21

标签: javascript jquery

我如何为下面的代码包含null?为什么有必要使用null?



$("a").each(function() {
    if (($(this).attr("href").indexOf(".PDF") > 1) || ($(this).attr("href").indexOf(".pdf") > 1)) {
          var url = $(this).attr("href");
          $(this).attr("onclick", "_gaq.push(['_trackEvent','Download','Document'," + "'" + url + "'" + "])");
    }
}); // to find the pdf links in a website

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

您好像希望确保只定位href.pdf的某些案例变体结尾的链接。只要您正确搜索符合条件的链接,您就不需要在此处测试null

这可以比你做得更简单:

&#13;
&#13;
var _gaq = [];

// Instead of looping over all the links and then checking each to see if it is a link you want,
// just get the links that you need to work with in the first place. Any links that don't match
// the criteria will simply be skipped.
// The "$=" means "ends-with and the "i" in the attribute selector indicates that 
// it is a case-insensitive search.
$("a[href$='.pdf' i]").each(function() {

    var url = $(this).attr("href");
    
    console.log(url); // <-- Just for demonstration to prove that only the right links were found
    
    // Don't set up inline event handlers, use modern standards
    $(this).on("click", function(event){
    
      console.clear();
      event.preventDefault(); // <-- This is just for this demonstration only
      
      _gaq.push(['_trackEvent','Download','Document', url]);
      console.log(_gaq);
    });
    
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a href="something.pdf">something.pdf</a>
<a href="something.html">something.html</a>
<a href="something.pDf">something.pDf</a>
<a href="something.jpg">something.jpg</a>
<a href="something.Pdf">something.Pdf</a>
&#13;
&#13;
&#13;