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

jQuery遍历DOM元素时外部作用域变量返回结果不符合预期问题

问题根本原因

你对jQuery的each()方法的返回值存在误解:

  • each()方法的设计定位是遍历jQuery对象,它的返回值永远是你调用它的原jQuery对象,和遍历回调函数里返回的内容没有任何关系。
  • 你在回调函数里返回device,只会中断当前这一次回调的执行,进入下一轮遍历,不会把这个值当作each()的返回结果。只有当你在回调里返回false时,才会直接终止整个遍历流程。

所以你当前的写法里,不管if判断是否成立,future_device拿到的永远是$(future_devices)这个对象,自然不可能返回空数组。


正确实现方案

你要筛选符合条件的元素,可以直接用jQuery的filter()方法,它是专门用来按条件过滤jQuery对象的API,返回值是只包含符合条件元素的新jQuery对象,没有匹配项就返回空jQuery对象,完全符合你的需求:

const future_devices = $('.hardware .future-hardware')
// 初始化为空jQuery对象,避免future_devices为空时变量未定义
let future_device = $()

if (future_devices.length) {
  future_device = future_devices.filter(function() {
    const deviceWorkOrder = $(this).data('work-order')
    return deviceWorkOrder === data['new_host']['work_order']
  })
}

如果你只需要第一个匹配到的元素,也可以提前声明变量存储结果,在each()遍历中赋值:

const future_devices = $('.hardware .future-hardware')
let future_device = $()

if (future_devices.length) {
  future_devices.each(function() {
    const deviceWorkOrder = $(this).data('work-order')
    if (deviceWorkOrder === data['new_host']['work_order']) {
      future_device = $(this)
      // 返回false终止遍历,不需要再校验后续元素
      return false
    }
  })
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 07:15:04