简体   繁体   English

如何获取任何父div单击哪个子div的id值

[英]How to get the id value of which child div is clicked of any parent div

Suppose I have a parent div which contains two more div which are created dynamically using jQuery. 假设我有一个父div ,其中包含另外两个div,这些div是使用jQuery动态创建的。 When I click on div one then it will alert or console its id value if I clicked on the second div then it will show the second div id attribute value 当我单击一个div时,如果我单击第二个div,它将提示或控制其id值,然后它将显示第二个div id的属性值

 for (i=0; i < 3; i++){ content = "<div class='dataToAppend' id="+i+" style='cursor:pointer; margin:30px; display:inline-block;'>" content += '<img id='+i+' src='+i+' >' content += "</div>" $(".data").append(content) } 
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <div class="data"></div> 

In this snippet when I click on one image then I want it console its id attribute 在此代码段中,当我单击一个图像时,我希望它控制其id属性

You can bind a delegated click event to the images: 您可以将委派的click事件绑定到图像:

 for (i = 0; i < 3; i++) { content = "<div class='dataToAppend' id='div" + i + "' style='cursor:pointer; margin:30px; display:inline-block;'>" content += '<img id=' + i + ' src=' + i + ' >' content += "</div>" $(".data").append(content) } $(".data").on('click', 'img', function() { // use a delegated event on the image console.log(this.id); // this is the image id console.log($(this).parent().attr('id')); // this is the div id }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <div class="data"></div> 

Please note that ids should be unique and you currently have your div and image ids being created the same, I edited above so they are different 请注意,这些ID应该是唯一的,并且您当前正在创建的div和图片ID相同(我在上面进行了编辑,因此它们是不同的)

Capture the click event in its bubbling phase on the .test element, check the event target, and, if it's a div then get the id else if it's an image get the id of its parentNode . 在冒泡阶段在.test元素上捕获click事件,检查事件目标,如果它是div则获取id ,如果是图像,则获取id ,获取其parentNodeid

You may use vanillaJS for this task 您可以将vanillaJS用于此任务

document.querySelector('.test').addEventListener('click', function(ev) {
  let tgt = ev.target;
  if (tgt.matches('div')) {
    console.log(tgt.id);
  }
  if (tgt.matches('img')) {
    console.log(tgt.parentNode.id);
  }
});

(As a side note, your id can't start with a digit) (请注意,您的ID不能以数字开头)

With vanilla JavaScript, you can just query all three .dataToAppend divs after the for loop and use the forEach() method to return the id of each element. 使用香草JavaScript,您可以仅在for循环之后查询所有三个.dataToAppend div,并使用forEach()方法返回每个元素的ID。


Check and run the following Code Snippet for a practical example of what I have described above: 检查并运行以下代码片段 ,以获得上述内容的实际示例:

 var data = document.querySelector(".data"); for (i=0; i < 3; i++){ content = "<div class='dataToAppend' id=imgDiv"+i+" style='cursor:pointer; margin:30px; display:inline-block;'>"; content += '<img id='+i+' src=img'+i+' >'; content += "</div>"; data.innerHTML += content; } var dataDivs = document.querySelectorAll(".dataToAppend"); dataDivs.forEach(div => { div.addEventListener("click", () => console.log(div.id)); }); 
 <div class="data"></div> 


NB In the above example, I have appended a non-numeric character for easier element targeting in CSS. 注意:在上面的示例中,我添加了一个非数字字符,以便在CSS中更轻松地定位元素。

You can use: 您可以使用:

$(document).on('click', '.dataToAppend img', function() {}

To add a click event to all your imgaes within the div with the class .dataToAppend . 为了与类专区内点击事件添加到您的所有imgaes .dataToAppend

Next, you can use $(this).attr('id'); 接下来,您可以使用$(this).attr('id'); to get the id of the image you clicked on. 获取您单击的图像的id

Also, I suggest you build up a string called content in your for loop (as .append() is a somewhat expensive method to run), and only once that is complete you .append() the content to your DOM. 另外,我建议您在for循环中建立一个名为content的字符串(因为.append()是一种运行起来比较昂贵的方法),只有完成后,您才将.append() content到DOM中。 This way you are only adding to the DOM once, rather than multiple times. 这样,您仅一次添加到DOM,而不是多次添加。

See working example below: 请参见下面的工作示例:

 let content = ""; for (i = 0; i < 3; i++) { content += "<div class='dataToAppend' id=" + i + " style='cursor:pointer; margin:30px; display:inline-block;'>" content += '<img id=' + i + ' src=' + i + ' >' content += "</div>" } $(".data").append(content); $(document).on('click', '.dataToAppend img', function() { let id = $(this).attr("id"); console.log(id); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <div class="data"></div> 

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

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