gpt4 book ai didi

javascript - querySelectorAll 返回的节点问题

转载 作者:行者123 更新时间:2023-11-30 14:03:29 27 4
gpt4 key购买 nike

我正在按类名实现外部点击 Hook

const useClickOutside = (className, f) => {

function handleClickOutside(event) {

if(event.which !== 1) return
const nodes = document.querySelectorAll(className)
console.log(nodes.length) // display the right length
console.log(nodes) // display the right elements
nodes.some((node) => { // falls
let outside = !node.contains(event.target)
if(outside) { f(); }
return outside
})

}

useEffect(() => {
document.addEventListener('mousedown', handleClickOutside);
return () => document.removeEventListener('mousedown', handleClickOutside);
}, []);

}

我是这样称呼钩子(Hook)的

useClickOutside(".foo", 
() => {
// some code ...
},
);

我得到了这个错误 TypeError: nodes.some is not a function 即使就在 some 函数之前我得到了节点数组上的所有东西!!

解决方案感谢@enapupe 的回答,我们也可以使用 ES6

const nodes = [ ...document.querySelectorAll(className) ]

最佳答案

The Document method querySelectorAll() returns a static (not live) NodeList representing a list of the document's elements that match the specified group of selectors.

https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll

NodeList 类型与具有一些 的数组类型不兼容。

您可以执行 Array.from(selector) 以便在其上使用常规数组原型(prototype)。

const useClickOutside = (className, f) => {
function handleClickOutside(event) {
if (event.which !== 1) return
const nodes = Array.from(document.querySelectorAll(className))
nodes.some((node) => {
let outside = !node.contains(event.target)
if (outside) {
f()
}
return outside
})
}

useEffect(() => {
document.addEventListener('mousedown', handleClickOutside)
return () => document.removeEventListener('mousedown', handleClickOutside)
}, [])
}

关于javascript - querySelectorAll 返回的节点问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55885947/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com