【问题标题】:jQuery: closest / parent not workingjQuery:最近/父级不工作
【发布时间】:2014-05-29 18:22:08
【问题描述】:

我有一个基本的 HTML 表格,每行都有一个按钮。 通过单击按钮,我想提醒来自同一 TR 中的第二个 TD 的文本。

由于某种原因,以下内容不起作用,要么不返回任何内容,要么返回 null(取决于我尝试使用 .text() 还是 .html() )。 parent 而不是最接近的也失败了。 有人可以告诉我我在这里做错了什么吗? (如果需要,我的表的 ID 为“myTable”,所有 TR 都在一个 TBODY 中。)

示例 TR:

<tr><td style="width:30%"><strong>Row 1:</strong></td><td id="fldRow1" style="width:60%">test text</td><td><button type="button" id="copyRow1" onclick="copyOutput()">Copy</button></td></tr>

JS函数:

function copyOutput() {
    var output = $(this).closest('tr').find('td:eq(1)').text();
    alert(output);
}

非常感谢您提供的任何帮助,蒂姆。

【问题讨论】:

  • 既然用的是jQuery,为什么还要用内联事件呢?
  • 谢谢。我也可以仅使用 JavaScript 来实现这一点吗?在这种情况下,我确实需要内联事件。
  • 嗯,jQuery 是 JavaScript,所以您已经只使用 JavaScript。不,在这种情况下你不需要内联事件。

标签: javascript jquery parent css-selectors closest


【解决方案1】:

this在你的代码中没有引用当前元素,它引用了窗口对象。

HTML

改变

onclick="copyOutput()"

onclick="copyOutput(this)" //pass refer of the current element


js
function copyOutput(el) { //el get current element clicked
    var output = $(el).closest('tr').find('td:eq(1)').text();
    alert(output);
}

【讨论】:

  • 完美 - 行得通!感谢您的快速帮助。我会尽快接受。
  • @user2571510 很高兴它有帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-08-08
  • 1970-01-01
  • 1970-01-01
  • 2012-08-05
  • 2011-01-19
  • 1970-01-01
  • 2013-03-25
相关资源
最近更新 更多