简体   繁体   English

Javascript获取父div的ID

[英]Javascript get id of parent div

I have the following structure: 我有以下结构:

<div id="accord1_1" class="panel-collapse collapse">
 <div class="panel-body">
   <div id="Dashboard">
    <div id="DashboardFlow">
     <div class="dashboard-caps">
      <div class="dashboard-info">
          <a class="save" onclick="return saveChanges();" href="#">Save</a>

When clicking on Save button i would like to get the parent div that is like accord%_1 . 当单击“保存”按钮时,我想获取类似于accord%_1的父div。 I'll explain myself better: 我会更好地解释自己:

I have like 30 structures like the one i've shown created. 我喜欢30种结构,就像我展示的那样。 All of them are exactly the same except from the id="accordX_1" key which is id="accord1_1" in the first collapsable panel, id="accord2_1" in the second and so on. 所有的人都一致,除了从同一个id="accordX_1"键是id="accord1_1"在第一可折叠面板, id="accord2_1"在第二等等。

What i need to do is get that id's value. 我需要做的就是获取该ID的值。

How can this be done? 如何才能做到这一点?

Regards, 问候,

Use closest and the startsWith selector 使用最近的startsWith选择器

$('.save').click(function(){
 var targetId = $(this).closest('div[id^=accord]')[0].id;
}); 

This will find the first matching parent element in the list of parent elements for the element with class=save, access the matched native element with [0], and the native .id property. 这将在具有class = save的元素的父元素列表中找到第一个匹配的父元素,使用[0]访问匹配的本机元素,以及native .id属性。

Just find the closest div on clicking save 只需单击save找到closest div

$("a.save").click(function(){

    var curr = $(this).closest("div.panel-collapse[id^=accord]") // Is the div you want;
    var id = curr.attr("id");

});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM