Reputation: 107
I'm trying to show/hide some content when I click on a tr and it is somehow not working. This is the simplified code:
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();
}
Upvotes: 0
Views: 533
Reputation: 240928
It's because this
refers to the window
object.
If you want this
to be bound to the clicked element, you could invoke the function with the .call()
method and pass this
.
<tr onclick="showDetails.call(this)"></tr>
Alternatively, you could also just pass a reference to this
as a parameter:
<tr onclick="showDetails(this)"></tr>
function showDetails(el) {
$(".hiddenContent").hide();
$(el).find(".hiddenContent").show();
}
The better approach would be to use unobtrusive JavaScript and attach an event listener to the tr
elements instead:
$('tr').on('click', function () {
$(".hiddenContent").hide();
$(this).find(".hiddenContent").show();
});
Upvotes: 3