有没有办法缩短 querySelector 结果并对其结果执行操作?最好在一行中?
想象有一个元素:
<div id="el">A</div>
以及相应的 JavaScript 代码:
const el = document.querySelector("#el");
el ? el.style.display = "none" : null;
假设 div#el
可能会或可能不会在页面上呈现(因此是三元运算符),有没有办法将上述逻辑缩短为一行?
答案 0 :(得分:0)
为什么不只是
Debug
如果 if 不匹配,你不需要做任何事情,所以我看不到使用三元的意义
答案 1 :(得分:0)
不要使用三元副作用。
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>
答案 2 :(得分:-1)
这就是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
时,它什么也不做,您是否拥有 Nothing
或 Just
由 maybeSelect
决定。
map
允许您转换值并使用 fold
来检索它。
当然,您可以随意链接 effect
和 map
。
这似乎有点矫枉过正,但一旦习惯了,就会上瘾。
如果您有兴趣,可以求助于诸如 Folktale 之类的图书馆。
答案 3 :(得分:-2)
好的,我找到了一个单线
[].filter.call([document.querySelector('#el')], el => el).forEach(el => el.style.display = "none");