click事件只获取父div



我在父元素而不是子元素上触发onclick事件时遇到问题。我有一个通过JavaScript创建的图像网格:

HTMLdiv:

将图像附加到此图像网格的JavaScriptdiv:

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:

#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代码:

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

当点击图像时,无论我点击哪里,该事件都会触发警报"图库网格"。从其他帖子来看,我希望事件首先发生在孩子身上,然后向父母靠拢,但出于某种原因,这里的情况并非如此。。。

有人知道我如何通过onclick事件访问"content"类div,将用户重定向到与他们单击的图像相关的页面吗?

谢谢

问题是由使用this而不是event.target.引起的

这段代码现在允许在所有父div上迭代,直到我找到我感兴趣的一个:

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

})

最新更新