18

解决实际问题的 24 个 ES6 代码段

 3 years ago
source link: https://www.infoq.cn/article/6Llkjz50xDIEfZvtjR7R
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

这篇文章基于实际使用场景总结了 24 个 ES6 代码段,可用来解决项目中可能遇到的一系列问题。

1. 如何隐藏所有指定元素?

复制代码

const hide = (...el) => [...el].forEach(e => (e.style.display = 'none'));

// Example

hide(document.querySelectorAll('img')); // 隐藏页面上的所有 <img> 元素

2. 如何确认元素是否具有指定的类?

复制代码

const hasClass = (el, className) => el.classList.contains(className);

// Example

hasClass(document.querySelector('p.special'), 'special'); // true

3. 如何切换元素的类?

复制代码

const toggleClass = (el, className) => el.classList.toggle(className);

// Example

toggleClass(document.querySelector('p.special'), 'special');

// 该段不再有 'special' 类


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK