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

jQuery的each方法中$(this)始终返回空数组是什么原因

问题原因

核心原因是箭头函数的this绑定规则和普通函数存在差异,具体逻辑如下:

  • jQuery的each()方法执行回调时,会默认将回调内部的this绑定为当前遍历到的DOM元素,该规则仅对普通函数生效。
  • 箭头函数没有独立的this指向,内部this会直接继承外层作用域的this,你代码中箭头函数外层的this指向的是getListItems运行时的上下文(全局调用时为window,严格模式下为undefined),并非期望的遍历项DOM元素,因此$(this)无法获取到对应元素,返回空的jQuery对象。

修复方案

两种常用方案都可以实现你要的简洁写法:

方案1:将箭头函数替换为普通匿名函数

function getListItems() {
  let items = [];
  const $items = $listElement.children('li');
  $items.each(function() {
    console.log($(this)); // 此时this为当前遍历的li DOM元素
    items.push($(this).html());
  });
  return items;
}

方案2:保留箭头函数,使用回调自带的元素参数

jQuery的each()回调支持传入第二个参数,直接对应当前遍历的DOM元素,不需要依赖this:

function getListItems() {
  let items = [];
  const $items = $listElement.children('li');
  $items.each((index, element) => {
    items.push($(element).html());
  });
  return items;
}

如果要进一步简化代码,可以直接用jQuery的map()方法直接生成目标数组:

function getListItems() {
  return $listElement.children('li').map(function() {
    return $(this).html();
  }).get();
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 00:45:06