将“th”的背景颜色更改为紧接着的下一个td

问题描述 投票:0回答:2

我想改变'th'元素的颜色后,我改变它旁边的'td'元素中的'input'元素。

这是我使用的jQuery脚本。

$('#phoneNo').change(function () {
    $(this).closest("tr").find("th").css("background-color","yellow");
    });

HTML代码

<tr>
    <th>PhoneNo</th>
    <td><input type="text" id="phoneNo"/></td>
    <th>EmailId</th>
    <td><input type="text" id="emailId"/></td>

</tr>

它的行为就像我所期望的那样 - 它改变了行中所有'th'元素(代码中的PhoneNo和EmailId)的背景颜色。但我想要的是改变只有一个'th'的颜色 - 就在相应的'td'之前的那个(只有PhoneNo)

javascript jquery css html-table
2个回答
1
投票
$('#phoneNo').change(function () {
    $(this).parent().prev("th").css("background-color","yellow");
});

请注意,由于.prev()正在寻找以前的兄弟姐妹,因此您需要首先找到td元素


0
投票
$('#phoneNo').change(function () {
    $(this).parent().prev('th').css("background-color","yellow");
});​

http://jsfiddle.net/zSjMh/1/看小提琴

© www.soinside.com 2019 - 2024. All rights reserved.