紀錄 Javscript 相關筆記

1. 用以下原生的 Javascript 語法來取代 jQyery 語法

Querying the DOM

1
2
3
jQuery('div.html')
document.querySelector('div.home')
document.querySelectorAll('img')

.html()

1
2
3
4
// 獲取 html
var htmlContent = document.querySelector('.main-div').innerHtml;
// 塞入 html
document.querySelector('.main-div').innerHtml = '<p>Hello World</p>';

.val()

1
2
3
4
// 取值
var inputValue = document.querySelector('.input-box').value;
// 賦值
document.querySelector('.input-box').value = 'Demo String';

.text()

1
let textValue = document.querySelector('.main-div').innerText;

Adding/Removing Classes

1
2
3
document.querySelector('#testElement').classList.add('testClass');

document.querySelector('#testElement').classList.remove('testClass')

Adding/Modifying CSS

1
2
3
document.querySelector('#testElement').style.color = '#ffffff';

document.querySelector('#testElement').style.backgroundColor = '#000000';

.attr()

1
2
document.querySelector('img').src = '/images/image.png';
document.querySelector('img').getAttribute('data-title');

.show() / .hide()

1
2
3
document.querySelector('.test-element').style.display = 'none';

document.querySelector('.test-element').style.display = 'block';

2. debounce(防抖)

1
2
3
4
5
6
7
8
9
const debounce = (fn, time) => {
  let timeout = null;
  return function() {
    clearTimeout(timeout)
    timeout = setTimeout(() => {
      fn.apply(this, arguments);
    }, time);
  }
};

3. throttle(節流)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
const throttle = (fn, time) => {
  let flag = true;
  return function() {
    if (!flag) return;
    flag = false;
    setTimeout(() => {
      fn.apply(this, arguments);
      flag = true;
    }, time);
  }
}