# Hi~前端工具們 - jQuery basic 2 ``` <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>jQ</title> <meta name="description" content="The HTML5 Herald"> <meta name="author" content="SitePoint"> <meta name="viewport" content="width=device-width, initial-scale=1"> <script src="jquery-3.6.0.js"></script> ``` ## jQuery 示範部分 `<script>` ``` $(document).ready(function(){ $('.btn').click(function(e){//按下按鈕後 const value = $('.todo_input').val() //把質拿出來(jquery裡面呼叫函式沒有傳東西就是get,有傳東西的時候就是set質) $('.todo_input').css('color','blue') //幫這個元素新增一個css $('.todo_input').val('') //拿到質後就後清空,變成空字串 //接著把質增加到.todos上去。 $('.todos').append(` <div class="todo"> ${value} <button class="btn_mark">done</button> <button class="btn_delete">delete</button> </div>`) }) ``` 把東西放進去的函式append()類似innerHTML, 還有一種叫prepend()往前面放 刪除就是remove() ``` $('.btn_remove_all').click(function(){ $('.todos').empty(); }) ``` - 清空,同等於innerHTML=''; 不可以用romove(),會把整個div刪除 - 刪除功能,要記得使用時間代理addEventListener 對todos監聽,click事件,對btn_delete作代理 在todos底下的每個btn_delete,click後,執行這個function ``` $('.todos').on('click','.btn_delete',function(e){ $(e.target).parent().fadeOut()//or remove() }) ``` - 標記完成功能 ``` $('.todos').on('click','.btn_mark',function(e){ const todo = $(e.target).parent(); if(todo.hasClass('completed')){ todo.css('text-decoration','none') todo.removeClass('completed') $(e.target).text('done') } else { todo.css('text-decoration','line-through') todo.addClass('completed') $(e.target).text('undone') } }) }); ``` `</script>` 其他 ``` <style> .todo{ padding: 12px; border: 1px solid grey; } </style> </head> <body> <input class="todo_input" type="text"/> <button class="btn">add todo</button> <button class="btn_remove_all">remove all todos</button> <div class="todos"> </div> <script> </script> </body> </html> ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up