[英]What is the shortest way to check a LONG written function for a valid output first (not null), and then to use it several times
Using vanilla js, I've put together a one liner that takes a long function, first checks to see if it has a valid value (not null), and if it has a valid value to use that long function several times in a shortened manner.使用 vanilla js,我整理了一个需要很长的 function 的衬里,首先检查它是否具有有效值(非空),如果它具有有效值以使用该长 function 多次缩短方式。
The code for it is something like this:它的代码是这样的:
(x => {if (!x) return; x.style.color='brown'; x.style.fontWeight='600';})(document.evaluate('//ul[@class="main-menu"]//li[text()="About"]', document, null, 9).singleNodeValue;);
The html it might work on would be something like this:它可能工作的 html 是这样的:
<ul class="main-menu">
<li>Home</li>
<li>About</li>
</ul>
The long way of doing it would be something like this:很长的路要走是这样的:
var x = document.evaluate('//ul[@class="main-menu"]//li[text()="About"]', document, null, 9).singleNodeValue;
if (x) {
x.style.color='brown';
x.style.fontWeight='600';
}
My final code is actually more like this:我的最终代码实际上更像这样:
const $e = (xpath) => { return document.evaluate(xpath, document, null, 9).singleNodeValue; }
(x => {if (!x) return; x.style.color='blue'; x.style.fontWeight='900';})($e('//ul[@class="main-menu"]//li[text()="Home"]'));
(x => {if (!x) return; x.style.color='brown'; x.style.fontWeight='600';})($e('//ul[@class="main-menu"]//li[text()="About"]'));
While I worked hard to make these one liners, I feel I could do something better.虽然我努力制作这些衬里,但我觉得我可以做得更好。
I leave this to the gurus to see if this can be improved upon please.我把这个留给大师看看是否可以改进。
If not, I'll just run with what I have, it seems to work...如果没有,我就用我所拥有的,它似乎工作......
The requirements are:要求是:
Thanks.谢谢。 Enjoy.
享受。 I look forward to any answers.
我期待着任何答案。
I found that Optional Chaining is the best method for me to go with my specific needs.我发现对于我来说,可选链接是 go 的最佳方法,以满足我的特定需求。
$e('//ul[@class="main-menu"]//li[text()="Home"]')?.style.color='blue';
Thanks for watching, wish someone could have suggested it.感谢观看,希望有人能推荐一下。
I'd thought this could have been a fun one for folks.我原以为这对人们来说可能很有趣。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.