2012-11-02 2 views
0

10 X 8 테이블이 있습니다.특정 테이블 "td"요소에 대한 정보 얻기

모든 행에는 8 개의 열, 즉 8 개의 요소가 있습니다. 행의 각 td에는 다른 클래스가 있습니다. 행의 다른 td 중 하나를 클릭하면 첫 번째 td 요소의 정보를 얻을 수 있습니까?

기본적으로 각 행의 2 열에서 8 열에 jquery onclick 이벤트가 생성됩니다. 이 열 (td) 중 하나를 클릭하면 즉, .. 정보, 즉 ID 또는 클래스 또는 이름 1 열의 속성을 가져와야합니다.이 값을 서버 쪽 코드로 보내야합니다.

- 감사합니다.

답변

2

예. (당신이 중첩 된 테이블을 경우에 아마 children) 클릭 된 요소에서, 당신은 closest를 통해 행까지 이동 한 다음 당신은 find 또는 children와 관련 클래스와 td을 찾을 수 있습니다

function clickHandler(e) { 
    var cell = $(e.target).closest('tr').children('td.foo'); 
    // ... 
} 

또는 경우를 항상이 원하는 td :

var cell = $(e.target).closest('tr').children('td').first(); 

가 어떠한 td에 할당하면 핸들러가 작동합니다 테이블을 tr 또는 실제로 tbody 또는 table 전체로

Live Example | Source

자바 스크립트 :

jQuery(function($) { 

    // Put the handler on the tbody 
    $("#target").click(clickHandler); 

    function clickHandler(e) { 
    var td = $(e.target).closest('tr').children('td').first(); 
    display("The text of the first <code>td</code> in that row is: " + td.text()); 
    } 

    function display(msg) { 
    $("<p>").html(String(msg)).appendTo(document.body); 
    } 

}); 

HTML :

<table> 
    <tbody id="target"> 
    <tr> 
    <td class="one">This is one in row 0</td> 
    <td class="two">This is two in row 0</td> 
    <td class="three">This is three in row 0</td> 
    </tr> 
    <tr> 
    <td class="one">This is one in row 1</td> 
    <td class="two">This is two in row 1</td> 
    <td class="three">This is three in row 1</td> 
    </tr> 
    <tr> 
    <td class="one">This is one in row 2</td> 
    <td class="two">This is two in row 2</td> 
    <td class="three">This is three in row 2</td> 
    </tr> 
    </tbody> 
</table> 
+0

감사합니다. Btw 하나의 작은 쿼리는 click 이벤트에 있는데, 이름 = "첫 번째 td의 이름 : value ="첫 번째 td의 값 "으로 숨겨진 입력을 추가 할 수 있습니까? - $ ("# tv-shows -feeds-form "). append ('

+1

@SangramAnand : ['td' 요소들] (http://www.w3.org/TR/html5/the-td-element.html#the-td-element)에는'name' 속성이나 (cell.attr ("name")'과'cell.val()'둘 다 아마도''''로 돌아올 것입니다). 원하는대로 필드를 추가 할 수는 있지만 셀의 어느 부분에서 이름과 값을 원하는지 알 수는 없습니다. (아마도 "값"에 의해 당신은 셀의 텍스트를 의미 할까? 그것은'cell.text()'일 것이다. 그러나 나는 그 이름이 무엇을 의미하는지 모른다.) 어쨌든 그것은 다른 질문 일 것이다. *이 * 질문에 대한 답변입니다. :-) –

+0

그래, 그 일. 고마워요. ..-) –

1

기본적으로 당신 같은 수 : 자세한 정보를 원하시면, 그 작업에 대한

$('td.column2-8').click(function() 
{ 
var firstTdData = $(this).parent().children('td:first').html(); 
}); 
1
$('td').click(function(){ 
    var $elem = $(this).parent('tr').children('td:first'); 
    var elem_id = $elem.prop('id'); // or $elem.attr('id'); 
    .... // for class, name, etc. 
});