简体   繁体   English

将 id 与点击元素 id 或动态内容的最整洁的父 id 匹配

[英]Matching id with click element id or neatest parent id of Dynamic Content

My HTML:我的 HTML:

...included jquery
<div id="step1">
  .. there are more child div
  <div id="step2">
    .. more child div
    <div id="step3">
      Selection 1
    </div>
  </div>
</div>

<div class="class-1">
  <div class="class-2">
    <div class="class-3">
      Section 2
    </div>
  </div>
</div>
...Some more neatest div and element

My Javascript:我的 Javascript:

$(document).click(function(event){
  let idNo = event.target.id;
  if(idNo == "step1"){
    # Do something
  }else{
    console.log(idNo); //print "step3"
    # Do others
  }
});

I'm trying to check if user click div which id is "step1" then do something.我正在尝试检查用户是否单击 id 为“step1”的 div,然后执行某些操作。 But event.target always contain child div information like in this case div which id is "step3".但 event.target 始终包含子 div 信息,例如在这种情况下 id 为“step3”的 div。 How can i check if clicking item have any neatest parent div with id "step1" Remember my content is dynamic so i can't set up click listener like $("step1").click();我如何检查单击项目是否有任何最整洁的父 div,id 为“step1”记住我的内容是动态的,所以我无法设置像$("step1").click();

We can write a simple function to get all the parent ids of an element:我们可以写一个简单的 function 来获取一个元素的所有父 id:

 function getParentIds(el) { let ids = []; while (el.parentNode) { let parentId = el.parentNode.id; if (parentId) ids.push(parentId); el = el.parentNode; } return ids; } // sample usage let element = document.querySelector('#three'); console.log(getParentIds(element)); // output: ['two', 'one']
 <div id="one"> <div id="two"> <div id="three"> Sample </div> </div> </div>

We can then attach this function our target nodes to determine their nearest parents (assuming there are no intermediate ids).然后我们可以附加这个 function 我们的目标节点以确定它们最近的父节点(假设没有中间 id)。

$('step1 *').click(function() {
  var parentIds = getParentIds(this);
  var nearestParent = parentIds[parentIds.length - 1];

  if (nearestParent == 'step1')) {/* do something for immediate children of step 1 */}
  else if (nearestParent == 'step2') {/* do something for immediate children of step 2 */}
  else { /* nearestParent is 'step3' */ }
})

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

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