JavaScript 練習 - 顧客心得

Demo

JavaScript 練習 - 顧客心得 - Demo

Introduction 介紹

這是一個網路上找到的練習題目,主要是網頁上常見的顧客心得區塊

  • 操作陣列索引值
  • 使用物件建構子
  • forEach()
  • 事件委派
  • 樣板字面值

功能

建立顧客資料

這裡要練習使用函式建構式 (function constructor),初始的陣列是一個空陣列,物件包含圖片索引、姓名、文字,當函式執行時當做參數傳入。其中圖片部分要利用樣板字面值與圖片索引取得圖片

利用關鍵字 new建立顧客資料的物件,並且將剛剛函式執行時傳入的參數用this指定到建立的空物件內容。再將產生的物件新增到空陣列裡面。

使用 new 這個關鍵字時,實際上會先有一個空的物件被建立。接著 People 這個函式會被執行(invoke)。我們知道當函式執行的時候,在 execution context 中會有 this 被建立,而當我們使用 new 的時候,函式裡面的 this 會被指定成剛剛所建立的那個空物件。[https://pjchender.blogspot.com/2016/06/javascriptfunction-constructornew.html](https://pjchender.blogspot.com/2016/06/javascriptfunction-constructornew.html)
1
2
3
4
5
6
7
8
9
10
11
12
13
let customers = [];
function Customer(img, name, text) {
this.img = img;
this.name = name;
this.text = text;
}

function createCustomer(img, name, text) {
let fullImg = `./img/customer-${img}.jpg`;
let customer = new Customer(fullImg, name, text);
customers.push(customer);
}
createCustomer(0, "John", "講解的很用心 範例也很多");

切換顧客心得

使用 querySelectorAll 選擇所有包含 btn 名稱的元素,使用此方法會得到一個類似陣列的 NodeList。因此接下來可以使用forEach(),將 nodelist 裡面的所有元素,都傳入函式執行一次。要執行的是監聽個別元素的點擊事件

1
2
3
4
5
buttons.forEach(function(button){
button.addEventListner('click',function){

}
})

這裡使用事件委派的方式,就省去個別綁定 button 的 click 事件的麻煩。把 click 事件改由外層的父節點來監聽,利用事件傳遞的原理,判斷 e.target 是我們要的目標節點,才去執行後續的動作。所以使用 2 個判斷式,判斷是否具備滿足條件,如果是,就往前或往後切換圖片

1
2
if (e.target.parentElement.classList.contains('prevBtn'))
if (e.target.parentElement.classList.contains('nextBtn'))

Powered by Hexo and Hexo-theme-hiker

Copyright © 2013 - 2020 CYC'S BLOG All Rights Reserved.

UV : | PV :