不能对单个元素使用querySelectorAll吗? [英] Can't use querySelectorAll for a single element?

查看:54
本文介绍了不能对单个元素使用querySelectorAll吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我了解在正常情况下,您可以使用querySelector选择单个元素,然后使用querySelectorAll选择多个元素.但是,我惊讶地发现querySelectorAll不能与单个元素一起使用.我希望它可以与一个或多个一起工作.我找不到任何提示它不能仅与之配合使用的东西,所以我在这里问这是否正常且符合规范?

I understand that under normal circumstances, you would use querySelector to select a single element and querySelectorAll for multiple. However, I was surprised to discover that querySelectorAll doesn't work with a single element. I expected it to work with one OR more. I can't find anything that says it shouldn't work with just one so I'm asking here if that's normal and according to spec?

HTML:

<div class="top container">
  <div class="pod" draggable="true">big</div>
  <div class="pod" draggable="true">small</div>
  <div class="pod" draggable="true">happy</div>
  <div class="pod" draggable="true">rich</div>
  <div class="pod" draggable="true">fast</div>
</div>

JS:

function dragStart(e) {
  console.log("drag started");
  e.target.style.opacity = "0.5";
}

与此配合使用(称为dragStart函数):

Works with this (dragStart function is called):

var topPods = document.querySelector(".top");
topPods.addEventListener("dragstart", dragStart);

但不能与此一起使用(未调用dragStart函数):

But doesn't work with this (dragStart function not called):

var topPods = document.querySelectorAll(".top");
topPods.addEventListener("dragstart", dragStart);

推荐答案

querySelectorAll 返回NodeList,而不是单个元素(即使查询结果只是一个元素).因此,您尝试将事件侦听器附加到该NodeList,而不是附加到元素.

querySelectorAll returns a NodeList, not a single element (even if the result of the query is only one element). So you are trying to attach an event listener to that NodeList, not to an element.

这确实有效(请注意 [0] ):

This does work (note the [0]):

var topPods = document.querySelectorAll(".top");
topPods[0].addEventListener("dragstart", dragStart);

这篇关于不能对单个元素使用querySelectorAll吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆