2012-05-03 22 views
0

我想在改變「td」元素旁邊的「input」elem後更改「th」元素的顏色。將「th」的背景顏色更改爲緊接着的下一個td

這裏是我使用的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> 

它的行爲就像我可以期待 - 它改變了所有的背景顏色「日」的行中的元素(包括PHONENO和EMAILID在代碼中)。但我要的是改變只有一個

+0

哦,我可以在每個'th'元素上使用'id'。我愚蠢。謝謝 –

回答

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

注意,因爲見琴「th' - 一個剛剛對應前面的‘TD’(僅PHONENO)的顏色.prev()正在尋找以前的兄弟姐妹,你需要先找到td元素