我试图在单击 tr 时显示/隐藏某些内容,但不知何故无法正常工作。这是简化的代码:
HTML:
<table>
<tr onclick="showDetails()">
<td>Some text
<br> <span class="hiddenContent">Some hidden content</span>
</td>
<td>Some More Text
<br> <span class="hiddenContent">Some hidden content</span>
</td>
</tr>
<tr onclick="showDetails()">
<td>Some text
<br> <span class="hiddenContent">Some hidden content</span>
</td>
<td>Some More Text
<br> <span class="hiddenContent">Some hidden content</span>
</td>
</tr>
</table>
JavaScript:
function showDetails() {
$(".hiddenContent").hide();
$(this).find(".hiddenContent").show();
}
最佳答案
因为this
引用了window
对象。
如果您希望this
绑定(bind)到被点击的元素,您可以使用.call()
method 调用该函数。并传递 this
。
<tr onclick="showDetails.call(this)"></tr>
或者,您也可以将对 this
的引用作为参数传递:
<tr onclick="showDetails(this)"></tr>
function showDetails(el) {
$(".hiddenContent").hide();
$(el).find(".hiddenContent").show();
}
更好的方法是使用 unobtrusive JavaScript并将事件监听器附加到 tr
元素:
$('tr').on('click', function () {
$(".hiddenContent").hide();
$(this).find(".hiddenContent").show();
});
关于javascript - $(this).find 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29132659/