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

Chrome扩展Popup中Element 'this'指向异常问题

Fixing this Binding Issue in Chrome Extension Popup Scroll Event

Ah, I’ve been there—arrow functions and jQuery event handlers can trip you up with this binding, especially in Chrome Extension popups! The core problem here is that arrow functions don’t create their own this context; they inherit it from the surrounding lexical scope, which in your case is the Popup’s global window object instead of the .activity-list div you’re targeting.

Here are three straightforward fixes to get your scroll trigger working correctly:

1. Switch to a Regular Function Expression

jQuery automatically sets this to the DOM element that fired the event when you use a traditional function. This is the simplest fix:

$('#activity-tab .activity-list').on('scroll', function() {
  // Now `this` refers directly to the .activity-list element
  if ($(this).scrollTop() + $(this).innerHeight() >= this.scrollHeight) {
    // Your business logic goes here
  }
});

Pro tip: I swapped .bind() for .on() since .bind() is deprecated in jQuery 3.0+. .on() does the exact same job but is the current recommended method.

2. Capture the Element Reference Upfront

If you want to keep using arrow functions (maybe you need to access variables from the outer scope), store the jQuery element in a variable first:

const $activityList = $('#activity-tab .activity-list');
$activityList.on('scroll', () => {
  // Use the pre-defined variable instead of relying on `this`
  if ($activityList.scrollTop() + $activityList.innerHeight() >= $activityList[0].scrollHeight) {
    // Your business logic here
  }
});

This avoids the this confusion entirely by referencing the element directly.

3. Use event.currentTarget in the Arrow Function

You can also grab the target element from the event object’s currentTarget property, which always points to the element the handler was attached to:

$('#activity-tab .activity-list').on('scroll', (event) => {
  const $target = $(event.currentTarget);
  if ($target.scrollTop() + $target.innerHeight() >= $target[0].scrollHeight) {
    // Your business logic here
  }
});

Any of these methods will resolve the this binding issue and let your scroll-based logic work as expected in your Chrome Extension’s Popup.

内容的提问来源于stack exchange,提问作者necroface

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 09:30:35