javascript - 如何获得与选择器匹配的最近的 parent 或 sibling ?

标签 javascript jquery html css

给定一个表:

<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> .

我希望它不是“过头了”^^

jsFFiddle

关于javascript - 如何获得与选择器匹配的最近的 parent 或 sibling ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19862785/

相关文章:

javascript - 添加多个 window.onload 事件

Javascript 和 HTML5 循环问题

javascript - DataTables 无法读取未定义的属性 'row'

jquery - 在 jQuery post 参数中使用对象

javascript - 如何在 Typescript 中为 Map 的类型别名定义索引签名?

javascript - 将 json 对象中每个深度级别的节点存储在单独的数组中

jQuery 水平滚动(点击时滑动 div)

html - 是否可以让 UIWebView 加载 html 字符串,但表现得像 UILabel

html - 如何制作动画文本以从图像中滑出?

html - <tbody> 标签显示在 chrome 但不是源