给定一个表:
<table border>
<tr>
<th rowspan=3>H1</th>
<td>1</td>
</tr>
<tr>
<td>2</td>
</tr>
<tr>
<td>3</td>
</tr>
<tr>
<th rowspan=3>H2</th>
<td>21</td>
</tr>
<tr>
<td>22</td>
</tr>
<tr>
<td>23</td>
</tr>
</table>
假设我们在“td”上有一个事件应该搜索最近的“th”(向上遍历 DOM)。例如,当点击 1、2 或 3 时,它应该返回 H1。点击21、22、23时,应该返回H2。
有什么想法吗?
最佳答案
这个怎么样:
$('td').click(function () {
if ($(this).parent().has('th').length > 0) {
$(this).parent().find('th').css('background', 'red');
//alert('first row!');
} else {
$(this).parent().prevAll('tr').has('th').first().find('th').css('background', 'red');
}
})
基本上我首先检查您是否选择了第一行,即包含 <th>
的行.
如果不是这种情况,我将搜索所有以前的 <tr>
元素(转到 DOM 结构的顶部)。
每当一个人有 <th>
元素它将在 .prevAll
中询问。我将选择第一个被选中的。
现在我们选择<th>
在选择<tr>
.
我希望它不是“过头了”^^
关于javascript - 如何获得与选择器匹配的最近的 parent 或 sibling ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19862785/