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

jQuery问题:为首个td添加点击事件跳转至相邻td的a标签链接

问题分析

你的代码核心问题在于:当你用attr('onClick', 'window.location = ' + $(this).next('td > a').attr('href'))时,字符串拼接中的$(this)并非指向当前的<td>元素,而是指向全局的window对象,导致无法找到目标<a>标签,最终attr('href')返回undefined。此外,就算能拿到URL,直接拼接也会因为缺少引号导致语法错误。

解决方案

方案一:遍历绑定点击事件(适合静态表格)

通过.each()遍历每个目标<td>,在当前元素的上下文里获取对应URL,再绑定点击事件:

$('tr td:first-of-type').each(function() {
  // 获取当前行第二个td里的a标签href
  const targetHref = $(this).siblings('td').find('a').attr('href');
  // 绑定点击跳转事件
  $(this).on('click', function() {
    window.location.href = targetHref;
  });
});

方案二:事件委托(推荐,支持动态新增行)

如果表格行是动态生成的,推荐将事件绑定到父容器(比如<table>),利用事件冒泡实现高效绑定:

$('table').on('click', 'tr td:first-of-type', function() {
  // 找到当前行第二个td内的a标签href
  const targetHref = $(this).closest('tr').find('td:nth-child(2) a').attr('href');
  // 存在href时才跳转,避免报错
  if (targetHref) {
    window.location.href = targetHref;
  }
});

方案三:修复内联事件写法(不推荐,维护性差)

如果一定要用内联onClick属性,需在遍历中拼接正确的字符串(注意给URL加引号):

$('tr td:first-of-type').each(function() {
  const targetHref = $(this).siblings('td').find('a').attr('href');
  $(this).attr('onClick', `window.location.href = "${targetHref}"`);
});
总结

优先选择事件委托的方式,不仅性能更优,还能兼容动态新增的表格行;内联事件尽量避免使用,不利于代码维护和调试。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 02:35:23