javascript - Div 单击事件不起作用 - jQuery

标签 javascript jquery html click

我已经查看了其他几个线程中的解决方案(大多数解决方案与此类似: div click event not working ),但我只是没有运气让点击事件在我的 div 上工作。见下面的js代码:

$(document).ready(function () {
    $(document).on('click', '#l1', function() {
        alert('clicked header');
    });
});

HTML:

<div id = 'main' class = 'container' style = 'height: 100%; width: 100%; float: left;'>
  <div id = 'left' class = 'container' style = 'height: 100%; width: 70%; float: left;'>
    <div id = 'l1' class = 'container bordered' align = 'right' style = 'height: 100%; width: 20%; float: left;'>
      <h1 id = 'l1Header'>Div Text</h1>
    </div>
  </div>
</div>

CSS:

html body {
  height: 100%;
  width: 100%;
}

.container {
  position: relative;
  z-index: -10;
}

.bordered {
  border: 2px solid #808080;
}

#main {
  font-size: 12px;
  text-align: right;
  font-family: sans-serif;
  line-height: 1.5;
  vertical-align: middle;
}

h1 {
  font-size: 18px;
  text-align: center;
  font-family: sans-serif;
  font-weight: normal;
  line-height: 1.5;
  vertical-align: top;
  z-index: 10;
}

有什么想法吗?

编辑:这是 z-index 的结果。后来在代码中,在 div 顶部添加了一个 svg,使其无法与之交互。谢谢大家!

最佳答案

我不太确定为什么要调用文档而不是仅将事件添加到元素中。我也不太确定你是想在这里使用 jQuery 还是 JS。你说的是 JS,但你使用的函数是 jQuery,并且只有在你使用 jQuery 库时才有效(如果你更了解的话,不是试图贬低)。尝试一下这个功能:

document.getElementById("l1").addEventListener("click", function(){
alert("Clicked Header");

});

这也可能与您的 z 索引有关。仅根据这段代码,不太确定为什么它们是必要的。

关于javascript - Div 单击事件不起作用 - jQuery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41788318/

相关文章:

javascript - jqGrid 在 RTL 方向的错误滚动位置

HTML/CSS : Making them elements besides eachother

javascript - ScrollMagic 在 IE11 中不工作

javascript - 非阻塞自定义错误

从文本中删除 bb_quotes ([quote..] [/quote]) 的 Javascript

javascript - 如何从本地机器加载图像到JS对象避免加载到服务器

c# - 服务器端代码中的 HTML 输入值。网站

html - 如何在表中的行之间添加间距?

javascript - 将表格单元格添加到现有表格行,jQuery

javascript - 信号器关闭连接