选择忽略子div

时间:2018-06-07 03:50:39

标签: javascript html css

我希望在选择容器的外部div时,我的alert函数应该不使用任何id或类名。

基本上我需要的是如果我有4个主要的div没有孩子。我应该能够向所有最外层的div添加一些事件,无论它有多少个子div。这可能吗?

var x = document.getElementsByTagName('DIV')[0];
x.addEventListener('click', function(e) {
  if (e.target == this) {
    alert('Outermost Div');
  }
})
.container {
  height: 200px;
  width: 60%;
  background: black;
  display: flex;
  justify-content: center;
  align-items: center;
}

.first-div {
  padding: 15px;
  background: white;
  height: 100px;
  width: 70%;
}

.first-div-child {
  padding: 15px;
  background: red;
}

.first-div-child>p {
  color: white;
}
<div class="container">
  <div class="first-div">
    <div class="first-div-child">
      <p> This is Para </p>
    </div>
  </div>
</div> <br>

<div class="container">
  <div class="first-div">
    <div class="first-div-child">
      <p> This is Para </p>
    </div>
  </div>
</div>

2 个答案:

答案 0 :(得分:0)

解决方案是将事件监听器添加到外部div中,方法是通过ClassName选择它们。这将能够解决您当前的问题

        <script>
        var x = document.getElementsByClassName('container');
        x.addEventListener('click',function(e) {
            if(e.target == this) {
                alert('Outermost Div');
            }
        })


    </script>

:)

答案 1 :(得分:0)

按类名而不是标记名选择div。这将返回一个[HTML Collection],其中包含您可以转换为真实数组的所有外部div,并使用forEach方法设置您的事件侦听器。您可以将event.currentTargetevent.target进行比较,并在它们相等时发出警报。请参阅下面的代码段:

var x = document.getElementsByClassName('container');
[...x].forEach( node => node.addEventListener('click', (e) => {
  if(e.currentTarget === e.target) console.log('outerMostDiv');
}));
.container {
  height: 200px;
  width: 60%;
  background: black;
  display: flex;
  justify-content: center;
  align-items: center;
}

.first-div {
  padding: 15px;
  background: white;
  height: 100px;
  width: 70%;
}

.first-div-child {
  padding: 15px;
  background: red;
}

.first-div-child>p {
  color: white;
}
<div class="container">
  <div class="first-div">
    <div class="first-div-child">
      <p> This is Para </p>
    </div>
  </div>
</div> <br>

<div class="container">
  <div class="first-div">
    <div class="first-div-child">
      <p> This is Para </p>
    </div>
  </div>
</div>