js

[jQuery] 버튼이 포함된 td의 부모 tr index 구하기

natrue 2021. 5. 18. 10:14
728x90

 $(this).parent().parent().index();

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
  <script>
  	$(document).ready(function() {
    	$("button").on("click", function() {
            var index = $(this).parent().parent().index();
            console.log("index : "+ index);
            $("#test").val(index); // test를 위한 input에 값넣기
        });
    });
  </script>
</head>
<body>

<div class="container">
	<input  id="test" type="text" class="inputbox" size="10" />
  <table class="table">
    <thead>
      <tr>
        <th>aaaaa</th>
        <th>aaaaa</th>
        <th>aaaaa</th>
        <th>aaaaa</th>
        <th>aaaaa</th>
      </tr>
    </thead>
    <tbody>
      <tr>
      	<td>aaaaa</td>
      	<td>bbbbb</td>
        <td>aaaaa</td>
        <td>bbbbb</td>
        <td><button type="button">click!!</button></td>
      <tr>
        <td>aaaaa</td>
        <td>bbbbb</td>
        <td>aaaaa</td>
        <td>bbbbb</td>
        <td><button type="button">click!!</button></td> 
      <tr>
        <td>aaaaa</td>
        <td>bbbbb</td>
        <td>aaaaa</td>
        <td>bbbbb</td>
        <td><button type="button">click!!</button></td>
      </tr>
      <tr>
        <td>aaaaa</td>
        <td>bbbbb</td>
        <td>aaaaa</td>
        <td>bbbbb</td>
        <td><button type="button">click!!</button></td>
       </tr>
    </tbody>
  </table>
</div>
</body>
</html>

 

$(this).parent(); - td

$(this).parent().parent(); - tr

$(this).parent().parent().index(); - tr의 인덱스 값