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

jQuery on change事件中调用closest()返回null问题排查

问题核心原因

你的代码逻辑错误出在closest()方法的使用上:

  • 当前遍历的$(this)本身就是class="dp-peso"的td元素,closest()的作用是向上查找匹配的祖先元素,所以这里closest('td')返回的是你当前正在操作的dp-peso元素本身
  • 这个td内部不存在class="dp-perce"的元素,后续find('.dp-perce')自然返回空,无法拿到对应的data属性值
  • 正确逻辑是先找到当前td所属的父级tr行,再在同一行内查找dp-perce元素

修正后的代码

$('#unit-type').on('change', function() {
  $('.dp-peso').each(function(){
      // 先定位到当前单元格所属的行,再查找同行的dp-perce元素
      var percentage = $(this).closest('tr').find('.dp-perce').data('perce');
      $(this).text(percentage);
  });
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 14:06:10