【问题标题】:click event only gets parent div点击事件只获取父 div
【发布时间】:2021-04-06 17:38:01
【问题描述】:

我遇到了在父元素上触发的 onclick 事件问题,但在子元素上却没有。 我有一个通过 JavaScript 创建的图像网格:

HTML div:

将图像附加到此图像网格 div 的 JavaScript:

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);
      });

点击图片时,无论我点击哪里,该事件都会触发警报“gallery-grid”。 从其他帖子中,我希望该事件首先在孩子身上触发,然后再向上发展到父母身上,但由于某种原因,这里并非如此......

有谁知道我如何使用我的 onclick 事件访问“内容”类 div,以将用户重定向到与他们点击的图像相关的页面?

谢谢

【问题讨论】:

  • 可能与事件冒泡和捕获有关。你可以在这里阅读更多:stackoverflow.com/questions/4616694/…
  • 提供的示例与问题有何关联?事件处理程序中的this 指的是附加事件的元素,如果您想要实际目标,请传递事件对象,然后检索event.target
  • 签出event.target vs event.currentTarget
  • 非常感谢您的帮助,问题确实是由于我误用了 this 而不是 event.target。我将发布我的更新代码,该代码现在迭代所有父元素,直到找到我感兴趣的类的 div

标签: javascript html css click grid-layout


【解决方案1】:

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

此代码现在允许遍历所有父 div,直到找到我感兴趣的:

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

})

【讨论】:

    猜你喜欢
    • 2017-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-03
    • 1970-01-01
    • 1970-01-01
    • 2012-12-07
    相关资源
    最近更新 更多