You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在以下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 an href attribute. 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 returns null. Trying to run indexOf() on null will throw a TypeError (since null isn'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:

  1. Store href in a variable: var linkHref = $(this).attr("href") saves us from querying the DOM twice for the same value, which is more efficient.
  2. Null/Truthy Check: linkHref && ... ensures we only proceed if linkHref is not null or undefined (since both are falsy values in JavaScript). This prevents the TypeError mentioned earlier.
  3. Fixed Extension Check: I changed > 1 to > -1 because indexOf() returns -1 when the substring isn't found. Using > -1 correctly checks if the PDF extension exists anywhere in the href, whereas >1 would 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:02:29