gpt4 book ai didi

javascript - 有没有办法为 querySelectors 编写 switch 语句或其他解决方案?

转载 作者:行者123 更新时间:2023-11-28 13:20:27 26 4
gpt4 key购买 nike

我目前有

if (element.querySelector('h1:first-child') || element.querySelector('container')) {
removeBorderClass();
}

if (element.querySelector('h3:first-child')) {
removeBorderClass();
}

但显然这在 JavaScript 中是一种不好的做法。

我可以使用 Switch 保护壳吗

switch(element.querySelector())
case 'h3:first-child' || 'container'
break;
//this is an example

或者有更好的解决方案吗?

<section>
<h1>h1 is first child of section</h1>
//it should remove the border
</section>

<section>
<h2>h1 is first child of section</h2>
//it should not remove the border
</section>

最佳答案

你不能像那样使用 switch/case,如果该模式重复很多,你可以将其重构为自己的函数:

function ifHasMatchingChildren(parent, selectors, callback) {
// or, if you want to get fancy
// if (selectors.some(parent.querySelector.bind(parent)) {
if (selectors.some(selector => parent.querySelector(selector))) {
return callback();
}
}

ifHasMatchingChildren(element, ['h1:first-child', 'container'], () =>
removeBorderClass());
// can even be shortened with the following
ifHasMatchingChildren(element, ['h3:first-child'], <strong>removeBorderClass</strong>);

关于javascript - 有没有办法为 querySelectors 编写 switch 语句或其他解决方案?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33613797/

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