简体   繁体   English

点击事件只获取父 div

[英]click event only gets parent div

I am having issues with onclick events triggered on parent elements but not on children.我遇到了 onclick 事件在父元素上触发但在子元素上没有的问题。 I have an image grid created through JavaScript:我有一个通过 JavaScript 创建的图像网格:

HTML div: HTML 分区:

JavaScript to append images to this image-grid div: JavaScript 到 append 图像到此图像网格 div:

var columnDiv = document.createElement('div');
columnDiv.setAttribute('class', 'column');

// create content div inside column
var contentDiv = document.createElement('div');
contentDiv.setAttribute('class', 'content');
contentDiv.setAttribute('data-animation_url', element['animation_url'])
contentDiv.setAttribute('data-image_url', element['image_url'])
// create image and append to contentDiv
var image = document.createElement('img');
image.setAttribute('src', image_gateway_url);
image.setAttribute('style', 'width:100%');
contentDiv.appendChild(image);
// add image name
var caption = document.createElement('span');
caption.setAttribute('class', 'image-name')
caption.innerHTML=element['name'];
contentDiv.appendChild(caption);

// append content div to column and append it to the grid
columnDiv.appendChild(contentDiv);
document.getElementById('image-grid').appendChild(columnDiv);

CSS: CSS:

#image-grid{
    margin: auto;
    position:absolute;
    z-index: -1;
}

.column {
    float: left;
    width: 25%; 
    height: 35vh;
    position: relative;
    z-index: 0;
  }

.content {
    background-color: white;
    padding: 10px;
    position: relative;
    z-index: 1;
  }

JavaScript code for click event: JavaScript 点击事件代码:

$('div').click(function() {
    var myClass = this.className;
    alert(myClass);
      });

When clicking on images, the event triggers the alert 'gallery-grid' wherever I click.单击图像时,无论我单击何处,该事件都会触发警报“图库网格”。 From other posts I would expect the event to trigger on children first then work its way up towards the parent but for some reason it is not the case here...从其他帖子中,我希望该事件首先在孩子身上触发,然后再向上发展到父母,但由于某种原因,这里的情况并非如此......

Does anyone happen to know how I could access the 'content' class div with my onclick event to redirect users to the page relevant to the image they clicked?有谁知道我如何通过我的 onclick 事件访问“内容”class div,以将用户重定向到与他们点击的图像相关的页面?

Thank you谢谢

The issue was caused by the use of this instead of event.target.该问题是由使用 this 而不是 event.target 引起的。

This code now allows to iterate over all parent divs until I find the one I am interested in:此代码现在允许遍历所有父 div,直到找到我感兴趣的那个:

    $('div').click(function(event) {
    let currentElement = event.target;
    while(currentElement.className != 'content') {
        currentElement=currentElement.parentNode;
    };
    alert(currentElement.className);

}) })

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

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