W12_jQuery 筆記


Posted by Christy on 2021-08-30

1. 為什麼要用 jQuery_簡介

FE201_再戰十年:jQuery_jQuery 簡介

這堂課稍微介紹一下 jQuery 的歷史,再說為什麼要用 jQuery,因為以前的(大概 2006)瀏覽器大概有五種,IE, safari, opera, chrome, firefox,因為規範還沒有很完整,一個功能有五種寫法,因此 jQuery 是來解決 Cross-Brower 的問題,他另一個賣點是簡化的語法

jQuery 官網


2. jQuery 選元素、改變文字內容、隱藏 / 顯示功能

FE201_再戰十年:jQuery_jQuery 基礎示範上集

如何引入 jQuery:

  1. 進去官網 download 區,選 Download the uncompressed, development jQuery 3.6.0,右鍵複製網址,貼在檔案的 標籤裡面
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="https://code.jquery.com/jquery-3.6.0.js"></script>
  <title>Document</title>
  <script>
    console.log(jQuery)
  </script>
</head>
  1. 02':48" 如何用 jQuery 加上點擊事件

a. 如果要把 js 寫在 head 裡面,那就要寫成下面的樣子

<script>
  console.log(jQuery)
  document.addEventListener('DOMContentLoaded', 
    function() {

  })
</script>

b. 用原生的寫法

<script>
  console.log(jQuery)
  document.addEventListener('DOMContentLoaded', 
    function() {
      document.querySelector('.btn').addEventListener('click', function() {
        alert('click')
      })
  })
</script>

c. jQuery 版本 04':00"

  • 要怎麼用 jQuery 選到想要的 DOM 元素?

    • 只要寫成 jQuery('.btn') 這樣就可以了
  • 針對 addEventListener,就用 .click(function(){}) 的方式

jQuery('.btn').click(function(e) {
  alert('clickjq')
})

d. $ 可以取代 jQuery,他其實是一個變數名稱

e. 原生跟 jQuery 是可以混用的

f. 可以都用 jQuery 語法

document.addEventListener('DOMContentLoaded', function() {
  $('.btn').click(function (e) {
    alert('click jq')
  })
})

可以寫成這樣 jQuery 語法

$(document).ready(function() {
  $('.btn').click(function(e) {
    alert('click jq')
  })
})

h. 怎麼選到物件

用 $('.box') -> 選到 class name = box 的物件
下面的是在說,點一下按鈕,把 box 裡面的 text 換成 'I am b box'

$(document).ready(function() {
  $('.btn').click(function(e) {
    $('.box').text('I am b box')
  })
})

i. .hide() 把東西藏起來;show() 顯示東西
fadeIn(2000);fadeOut(2000)

範例程式碼

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="https://code.jquery.com/jquery-3.6.0.js"></script>
  <title>Document</title>
  <script>
    var isHide = false
    $(document).ready(function() {
      $('.btn').click(function(e) {
        if (isHide) {
          $('.box').fadeIn(2000)
        } else {
          $('.box').fadeOut(2000)
        }
        isHide = !isHide
      })
    })
  </script>
  <style>
    .box {
      width: 200px;
      height: 200px;
      background: grey;
    }
  </style>
</head>
<body>
  <button class="btn">I am a button</button>
  <div class="box">box</div>
</body>
</html>

我的發現:

  1. 原來 裡面也可以放 標籤而且執行程式碼!但其實放在 body 最下面比較好,程式碼才會跑
    如果要這樣寫,就要寫成上面 2. a 的樣子

3. jQuery todo list 新增功能

FE201_再戰十年:jQuery_jQuery 基礎示範下集

  1. 先把按鈕加上監聽事件

  2. 把輸入框的值拿出來 $('.todo-input').val()

  3. 如果 value 裡面有東西,就是設定值,像是 placeholder 那種感覺 $('.todo-input').val('abc')

  4. jQuery 有趣的地方在於,用同一個函式,拿東西就是 2;設定就是 3

  5. 整個邏輯就是:

a. 按鈕加監聽事件

b. 把輸入框的值拿出來

c. 輸入框清空 $('.todo-input').val('')

d. 把內容加到下面的 div 標籤裡面

$('.todos').append(

${value}
)

e. prepend() 新增的值往前面長(最新的放在最上面)

操作指令:jQuery 官方文件 Manipulation

這裡也可以查指令:You might not need jQuery

f. 輸入文字顏色變紅色 $('.todo-input').css('color', 'red')

g. 示範程式碼

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="https://code.jquery.com/jquery-3.6.0.js"></script>
  <title>Document</title>
  <script>
    $(document).ready(function() {
      $('.btn').click(function(e) {
        const value = $('.todo-input').val()
        $('.todo-input').css('color', 'red')
        $('.todo-input').val('')
        $('.todos').prepend(`<div class="todo">${value}</div>`)
      })
    })
  </script>
  <style>
    .todo {
      border: 1px solid grey;
      padding: 10px;
    }
  </style>
</head>
<body>
  <input class="todo-input" />
  <button class="btn">Add todo</button>
  <div class="todos">

  </div>
</body>
</html>

4. jQuery 實作 todo list 標記完成、刪除、刪除全部

FE201_再戰十年:jQuery_jQuery 實戰 - todo list

利用之前做的新增接著做,有標記完成、刪除、刪除全部

  1. 在動態新增 todo 裡面,加上兩個按鈕:標記完成跟刪除

  2. 02':04" 刪除功能

當按下刪除按鈕時,刪除整列清單;這裡要監聽的是上層的父元素,也就是「不是」刪除按鈕本身,而是 todos,因為 todos 包含所有的 todo

on() 事件代理,裡面有三個參數,第一個放事件,第二個放要被代理的 class name
$(e.target) 這樣 e.target 才會變成 jQuery 的物件

$('.todos').on('click', '.btn-delete', function(e) {
        $(e.target).parent().remove()
      })
  • 在這裡遇到的困難是:

如果把按鈕再包一層起來,這樣監聽事件的時候,就會抓不到父層元素。

原因是我想要解決待辦清單跟按鈕中間要有空隙,本來想要用 justify-content: space-between,後來我把待辦清單加上寬度就可以了。

<div class="todo-list">
  <div class="list-group-item">
    <div class="todo">${value}</div>
    <button class="btn mark">done</button>
    <button class="btn edit">edit</button>
    <button class="btn delete">delete</button>
  </div>  
</div>
  1. 05':10" 標記完成

標記完成因為也是動態新增的按鈕,所以也要用事件代理。

遇到的困難:

  1. 本來想要用刪除線的,但發現用事件代理,所以的文字都被我加上刪除線了,後來替代方案是改變文字顏色,就沒有這個困擾了,但我不明白為什麼。

  2. 要注意 css 不要把顏色寫死,不然在動態新增的時候,顏色無法改變。

  3. 09':30" 刪除所有 todo

其實就是把整個 todos 的 div 清空,用 empty() 這個函式比較好,如果用 remove(),是把整個 div 刪除,這樣之後就不能新增了

empty() => innerHTML = ' '

$('.btn-remove-all').click(() => {
  $('.todos').empty()
})

5. 利用 jQuery 發 request 拿到資料

FE201_再戰十年:jQuery_jQuery 與 Ajax

google key word: jQuery ajax example

  1. jQuery.ajax() => $.ajax()
<script>
  $.ajax({
    method: 'GET',
    url: 'https://restcountries.eu/rest/v2/name/taiwan'
  }).done(function(data) {
    console.log(data)
  })
</script>

如果只要用 GET 拿資料的話,可以簡寫成下面那樣

<script> $.ajax('https://restcountries.eu/rest/v2/name/taiwan').done(function(data) {
    console.log(data)
  })
</script>
  1. 06':00" 做錯誤處理 .fail()
<script>
  $.ajax({
    url: 'https://aarestcountries.eu/rest/v2/name/taiwan',
    success: data => console.log(data),
    error: err => console.log('err', err)
  })
</script>
  1. 最後長這樣
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="https://code.jquery.com/jquery-3.6.0.js"></script>
  <title>Document</title>
</head>
<body>
  <script>
    $(document).ready(() => {
      $('.btn').click(() => {
        const value = $('input[name=country-name]').val()
        if (value === '') {
          alert('必須輸入名稱')
          return
        }

        $('.list').empty()
        $.ajax({
          method: 'GET',
          url: 'https://restcountries.eu/rest/v2/name/' + value,
          success: countries => {
            for (let country of countries) {
              $('.list').append(
                `<div>${country.alpha2Code} ${country.name} ${country.nativeName}</div>`
              )
            }
          },
          error: err => alert('系統不穩定')
        })  
      })
    })
  </script>
  Name: <input name="country-name" /> <button class="btn">送出</button>
  <div class="list">
  </div>
</body>
</html>

6. jQuery 總結

FE201_再戰十年:jQuery_jQuery 總結

可以用 jQuery UI 做出動畫,把 css 跟 jQuery 引入即可










Related Posts

PHP 語法基礎

PHP 語法基礎

為狀態機各個狀態加上名稱吧

為狀態機各個狀態加上名稱吧

Customizing a Laptop Through Engraving is a Great Personalization Idea

Customizing a Laptop Through Engraving is a Great Personalization Idea


Comments