简体   繁体   English

从父 ID 拆分并显示子 ID

[英]Split and display Child ID from Parent ID

I have a div with ID as "parentID" to the parent div and based on this, I am dynamically adding "ChildID" to all its child divs along with its "parentID".我有一个 div,其 ID 为父 div 的“parentID”,基于此,我动态地将“ChildID”添加到其所有子 div 及其“parentID”。

 jQuery(document).on('click', '.split-id', function() { var parentID = jQuery('.parent').attr('id'); var childID = jQuery('.child').attr('id', jQuery(this).closest('.parent').attr('id') + 'ChildID'); jQuery('#displayParentID').html('Parent ID : ' + parentID); jQuery('#displayParentChildID').html('Parent Child ID : ' + childID); jQuery('#displayOnlyChildID').html('Child ID only : ' + childID); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <div class="parent" id="parentID"> <div class="child"></div> <div class="child"></div> </div> <div id="displayParentID"></div> <div id="displayParentChildID"></div> <div id="displayOnlyChildID"></div> <a href="javascript:;" class="split-id">Split</a>

How can I get all child element IDs without parent div IDs?如何在没有父 div ID 的情况下获取所有子元素 ID? like below onClicking of Split tag...像下面 onClicking 的Split标签...

Parent ID : parentID父 ID : 父 ID
Parent Child ID : parentIDChildID父子 ID : parentIDChildID
Child ID only : ChildID ( This is what I am expecting )仅儿童 ID: ChildID这是我所期望的

Fiddle小提琴

Don't know what exactly is purpose of what you are asking, but you can replace your js code in your fiddle with this and it works as you expected.不知道您所要求的究竟是什么目的,但是您可以用这个替换您小提琴中的 js 代码,它可以按您的预期工作。 * Mind that, when you use attr function to set a property it is returning Object, not only string label. * 请注意,当您使用 attr 函数设置属性时,它返回的是 Object,而不仅仅是字符串标签。 * If you will give multiple children the same id it will not work, because in html code ids need to be unique * 如果你给多个孩子相同的 id 它将不起作用,因为在 html 代码中 id 需要是唯一的

jQuery(document).on('click', '.split-id', function () { 

  var parentID = jQuery('.parent').attr('id');
  var childElement = jQuery('.child').attr('id', parentID + 'ChildID');
  var childID = childElement.attr('id');
  jQuery('#displayParentID').html('Parent ID : ' + parentID);
  jQuery('#displayParentChildID').html('Parent Child ID : ' + childID);
  jQuery('#displayOnlyChildID').html('Child ID only : ' + childID.replace(parentID, ''));  

});

If you have some more questions, go on and ask.如果您还有其他问题,请继续提问。

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

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