gpt4 book ai didi

javascript - querySelector 和 querySelectorAll 别名

转载 作者:行者123 更新时间:2023-11-30 07:02:06 24 4
gpt4 key购买 nike

<分区>

querySelector 创建跨浏览器别名的最佳替代方案是什么?和 querySelectorAll对于documentElement

最直接的方法可能是

window.$ = function(selector){return document.querySelector(selector)}
window.$$ = function(selector){return document.querySelectorAll(selector)}

当然这不允许链接,因为函数返回总是指向 document

$('.parent-class').$$('.child-classes')

到目前为止我最好的选择是

window.$ = document.querySelector.bind(document);
window.$$ = document.querySelectorAll.bind(document);
Element.prototype.$ = Element.prototype.querySelector;
Element.prototype.$$ = Element.prototype.querySelectorAll;

这样我们就可以执行之前失败的选择器,虽然我不确定这可能带来的不良影响,有没有人可以提供提示/解释?

有没有人有好的不引人注目的替代方案?

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