2017-04-13 47 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>