2017-04-13 21 views
-2

divの中にテーブルがあります。親DIVのIDを取得

<div id="aaa"> 
    <table> 
     <tr> 
      <td> 
       <button></button> 
      </td> 
     </tr> 
    </table> 
</div> 

「aaa」のdivのIDをボタンから取得するにはどうすればよいですか?私は最も近い親を使用しようとしましたが、それは私に「未定義」出力を与えます。

$(this).closest('div').attr('id'); 
+0

それは私のために完璧に動作します。ボタンは「this」ですか? – Neil

答えて

0

これを試すことができます。どうぞ。コーディングを続ける!

function findID(){ 
 
    var id = $("button").closest("div").prop("id"); 
 
    $("#display").text(id); 
 
}
button { 
 
    background-color: black; 
 
    border: 0; 
 
    color: white; 
 
    width: 100px; 
 
    height: 30px; 
 
} 
 

 
#display { 
 
    margin-top: 40px; 
 
    width: 100px; 
 
    text-align: center; 
 
}
<script 
 
    src="https://code.jquery.com/jquery-3.2.1.min.js" 
 
    integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" 
 
    crossorigin="anonymous"></script> 
 
<div id="aaa"> 
 
    <table> 
 
     <tr> 
 
      <td> 
 
       <button onclick="findID()">Find ID</button> 
 
      </td> 
 
     </tr> 
 
    </table> 
 
</div> 
 
<div id="display"></div>

関連する問題