如何在以下jQuery PDF链接追踪代码中加入null判断?为何需用null?
Adding Null Checks to Your PDF Tracking jQuery Code
First, let's break down why a null check is absolutely necessary here:
- Not every
<a>tag on your site has anhrefattribute. For example, some anchors might be used for in-page navigation without an href, or dynamic elements that haven't been fully initialized. - When you call
$(this).attr("href")on an anchor without an href, it returnsnull. Trying to runindexOf()onnullwill throw a TypeError (sincenullisn't a string), which can break other JavaScript on your page.
Modified Code with Null Check
Here's how to update your code to include the null check, plus a small optimization to avoid repeating the attr("href") call:
$("a").each(function() { // Store the href value once to avoid redundant DOM queries var linkHref = $(this).attr("href"); // First check if linkHref exists (not null/undefined), then check for PDF extensions if (linkHref && (linkHref.indexOf(".PDF") > -1 || linkHref.indexOf(".pdf") > -1)) { $(this).attr("onclick", "_gaq.push(['_trackEvent','Download','Document'," + "'" + linkHref + "'" + "])"); } });
Key Changes Explained:
- Store
hrefin a variable:var linkHref = $(this).attr("href")saves us from querying the DOM twice for the same value, which is more efficient. - Null/Truthy Check:
linkHref && ...ensures we only proceed iflinkHrefis notnullorundefined(since both are falsy values in JavaScript). This prevents the TypeError mentioned earlier. - Fixed Extension Check: I changed
> 1to> -1becauseindexOf()returns-1when the substring isn't found. Using> -1correctly checks if the PDF extension exists anywhere in the href, whereas>1would miss cases where the extension starts at position 0 or 1 (like".pdf"or"x.pdf").
Why Use Null Specifically?
While checking for truthiness (linkHref && ...) covers both null and undefined, explicitly checking linkHref !== null would also work. The truthy check is more concise here because it handles edge cases where href might be an empty string ("") as well, which you probably don't want to track anyway.
内容的提问来源于stack exchange,提问作者bsen
相关产品推荐
相关产品推荐

