- HTML5 Web Application Development By Example Beginner's Guide
- J.M. Gustafson
- 187字
- 2021-08-13 16:50:20
Time for action – moving tasks within the list
While we're at it, let's add buttons to move tasks up and down in the list. For this we'll add some more code to the addTaskElement()
method. First we need to create move-up
and move-down
buttons, and then add them to the list element along with the delete
button.
function addTaskElement(taskName) { var $task = $("<li></li>"); var $delete = $("<button class='delete'>X</button>"); var $moveUp = $("<button class='move-up'>^</button>"); var $moveDown = $("<button class='move-up'>v</button>"); $task.append($delete) .append($moveUp) .append($moveDown) .append("<span class='task-name'>" + taskName + "</span>"); $("#task-list").append($task); $delete.click(function() { $task.remove(); }); $moveUp.click(function() { $task.insertBefore($task.prev()); }); $moveDown.click(function() { $task.insertAfter($task.next()); }); }
When the move up or move down button is clicked, it finds the previous or next task element using the prev()
and next()
methods. Then it uses the jQuery insertBefore()
and insertAfter()
methods to move the task element up or down in the tasklist.
What just happened?
We added buttons to each task element so that we can delete them or move them up and down in the order of the list. We learned how to use the jQuery remove()
, insertBefore()
, and insertAfter()
methods to modify the DOM.
推薦閱讀
- Web前端開發技術:HTML、CSS、JavaScript(第3版)
- 精通JavaScript+jQuery:100%動態網頁設計密碼
- JavaScript 從入門到項目實踐(超值版)
- GeoServer Cookbook
- CockroachDB權威指南
- Oracle Database In-Memory(架構與實踐)
- Vue.js 3.0源碼解析(微課視頻版)
- C語言程序設計立體化案例教程
- 精通API架構:設計、運維與演進
- MySQL數據庫管理與開發實踐教程 (清華電腦學堂)
- Mastering Android Development with Kotlin
- Microsoft Azure Storage Essentials
- Java語言程序設計教程
- Julia 1.0 Programming Complete Reference Guide
- 深入理解C指針