2017-04-13 61 views
-2

我有一個表格內的div。獲取父DIV

<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>