[英]jQuery: closest / parent not working
我有一个基本的HTML表,每一行都有一个按钮。 通过单击按钮,我要在同一TR中提醒第二个TD的文本。
由于某种原因,下面的代码不起作用,并且不返回任何内容或返回null(取决于我尝试使用.text()还是.html())。 父级而不是最接近的失败。 有人可以告诉我我在做什么错吗? (如果需要,我的表的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);
}
蒂姆,非常感谢您对此提供的任何帮助。
您代码中的this
不引用当前元素,而是引用窗口对象。
的HTML
更改
onclick="copyOutput()"
至
onclick="copyOutput(this)" //pass refer of the current element
function copyOutput(el) { //el get current element clicked var output = $(el).closest('tr').find('td:eq(1)').text(); alert(output); }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.