缩短 querySelector 和样式更改

问题描述

有没有办法缩短 querySelector 结果并对其结果执行操作?最好在一行中?

想象有一个元素:

<div id="el">A</div>

以及相应的 JavaScript 代码

const el = document.querySelector("#el");

el ? el.style.display = "none" : null;

假设 div#el 可能会或可能不会在页面上呈现(因此是三元运算符),有没有办法将上述逻辑缩短为一行?

解决方法

为什么不只是

Debug

如果 if 不匹配,你不需要做任何事情,所以我看不到使用三元的意义

,

不要使用三元副作用。

if 更容易阅读

const el = document.getElementById("el");
if (el) el.hidden=true;
<div id="el">A</div>

较短的相同结果:

#el { display: none }
<div id="el">A</div>

单线

document.querySelectorAll("#el").forEach(el => el.hidden=true);
<div id="el">A</div>

,

这就是Maybe的优点

const maybeSelect = selector => {
   const elem = document.querySelector(selector);
   return elem ? Just(elem) : Nothing();
};
maybeSelect('#el').effect(x => x.style.display = 'none');

一个简单(糟糕)的实现

const Just = (value) => ({
   fold: (f = x => x) => f(value),map: f => Just(f(value)),effect: f => (f(value),Just(value))
})

const Nothing = () => ({
   fold: () => null,map: f => Nothing(),effect: f => Nothing()
})

基本上,当您在 effect 上使用 Nothing 时,它什么也不做,您是否拥有 NothingJustmaybeSelect 决定。

map 允许您转换值并使用 fold 来检索它。

当然,您可以随意链接 effectmap

这似乎有点矫枉过正,但一旦习惯了,就会上瘾。

如果您有兴趣,可以求助于诸如 Folktale 之类的图书馆。

,

好的,我找到了一个单线

[].filter.call([document.querySelector('#el')],el => el).forEach(el => el.style.display = "none");

取自这里: https://stackoverflow.com/a/42532205/10684798