如何为多个 div 的内部/外部事件“单击”设置条件?

html我有js如下所示:


document.addEventListener('click', myFunction())


function myFunction(e) {

  let inputs = document.querySelectorAll('.my-element');

  let m = inputs.forEach((el) => el.contains(e.target));

  if (!m) {

    console.log('Element');

  }

}

<div class="my-element" style: "width:100px; height: 100px">

</div>

<div class="my-element" style: "width:100px; height: 100px">

</div>

<div class="my-element" style: "width:100px; height: 100px">

</div>

问题是,即使我在目标内部单击,条件仍然有效。我需要条件仅在我单击元素外部时才有效。我的错误是什么?



拉风的咖菲猫
浏览 169回答 3
3回答

慕森王

如果您希望单击事件仅在不超过某些元素时触发,您必须检查事件目标是否与那些元素不同除了将 m 的值设置为始终返回未定义的 forEach,然后检查 !m 这将始终为真之外,您几乎拥有它只需从节点列表中创建一个新数组并将 m 设置为 .find 值,这样一来document.addEventListener('click', myFunction)function myFunction(e) {&nbsp; let inputs = document.querySelectorAll('.my-element');&nbsp; let titles = document.querySelectorAll('.my-title');&nbsp; let m = Array.apply(0,inputs).find((el) => el.contains(e.target));&nbsp; if (!m) {&nbsp; &nbsp; console.log('Element');&nbsp; }}

森林海

这里:因为inputs是节点列表,所以需要将其转换为数组。我在这里用传播运算符完成了我...你也可以这样做Array.from,[].concat(inputs)然后为您过滤数组e.target并检查长度是否为 0。document.addEventListener('click', myFunction)function myFunction(e) {&nbsp; let inputs = document.querySelectorAll('.my-element');&nbsp; let m = [...inputs].filter(el => el === e.target);&nbsp; if (!m.length) {&nbsp; &nbsp; console.log('Element');&nbsp; }}<div class="my-element" style="background: black;margin: 10px;width:100px; height: 100px"></div><div class="my-element" style="background: black;margin: 10px;width:100px; height: 100px"></div><div class="my-element" style="background: black;margin: 10px;width:100px; height: 100px"></div>

青春有我

()从刚刚使用myFunction中删除。document.addEventListener('click', myFunction())document.addEventListener('click', myFunction)您可以使用Element.matches()with targetase.target.matches('.my-element')并验证它是否是您想要的。matches将selector作为parameter.在下面的示例中尝试,当您单击label或input它什么也不会log。当您单击其他部分时,div它会log。document.addEventListener('click', myFunction);function myFunction(e) {&nbsp; //let inputs = document.querySelectorAll('.my-element');&nbsp; //let titles = document.querySelectorAll('.my-title');&nbsp; //let m = inputs.forEach((el) => el.contains(e.target));&nbsp; if (e.target.matches('.my-element')) {&nbsp; &nbsp; console.log('Element', e.target.innerText);&nbsp; }}<div class="my-element" style: "width:100px; height: 100px">&nbsp; <label>abcd</label></div><div class="my-element" style: "width:100px; height: 100px"><input type='text' value='input' /></div><div class="my-element" style: "width:100px; height: 100px">c</div>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript