테이블 열 선택 (jQuery)
-
18-09-2019 - |
문제
나는 모든 것을주고 싶다 (포함 <th>
) 첫 번째 및 마지막 열의 셀, 일부 특정 클래스, 나는 이것을 시도했다 :
$("table tr:first-child td:first-child").addClass("first-col-cell");
$("table tr:last-child td:last-child").addClass("last-col-cell");
..하지만 작동하지 않는 것 같습니다.
어떤 도움에 감사 할 것입니다.
해결책
편집 : 선택기는 매우 가깝습니다.
<script type="text/javascript">
$(function() {
$("table tr td:first-child").text('hello');
$("table tr td:last-child").text('goodbye');
});
</script>
<table>
<tr>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
</tr>
</table>
다른 팁
만약에 th
요소가 중요합니다 ... Colspans를 어떻게 처리하고 싶은지 잘 모르겠습니다.
<!doctype html>
<table>
<tr>
<th></th>
<td>blah</td>
<td></td>
</tr>
<tr>
<td colspan="2"></td>
<td></td>
</tr>
<tr>
<td></td>
<td>blah</td>
<td></td>
</tr>
<tr>
<td></td>
<td>blah</td>
<td></td>
</tr>
</table>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$("table tr :first-child").text('first').css('background', 'yellow');
$("table tr :last-child").text('last').css('background', 'brown');
});
</script>
조금 분해 해보세요. 당신이하고있는 순회가 잘못되었습니다.
// This will take the first child which is a TD, within any TR in the table.
$("table tr td:first-child").addClass("first-col-cell");
// This will take the first child which is a TR within the table.
$("table tr:first-child").addClass("first-col-cell");
// Just like the above, except now we're doing the last occurances
$("table tr td:last-child").addClass("last-col-cell");
$("table tr:last-child").addClass("last-col-cell");
그런 다음 우리는 마크 업이 모두 좋는지 확인해야합니다.
<table>
<tr>
<td>1</td>
<td>1</td>
<td>1</td>
<td>1</td>
</tr>
<tr>
<td>2</td>
<td>2</td>
<td>2</td>
<td>2</td>
</tr>
<tr>
<td>3</td>
<td>3</td>
<td>3</td>
<td>3</td>
</tr>
그런 다음 jQuery는 다음 결과로 각각을 통과해야합니다.
<table>
<tr class="first-col-cell">
<td class="first-col-cell">1</td>
<td>1</td>
<td>1</td>
<td class="last-col-cell">1</td>
</tr>
<tr>
<td class="first-col-cell">2</td>
<td>2</td>
<td>2</td>
<td class="last-col-cell">2</td>
</tr>
<tr class="last-col-cell">
<td class="first-col-cell">3</td>
<td>3</td>
<td>3</td>
<td class="last-col-cell">3</td>
</tr>
</table>
제휴하지 않습니다 StackOverflow