typescript todoList例子

本文介绍如何使用HTML和TypeScript创建一个简单的TODO应用,包括待办事项的添加、状态管理和列表渲染。通过实际代码示例,展示了从类定义到DOM操作的全过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

html文件 引入的是 todo.js  (ts转后的js)

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>todo</title>
  <style>
    .item-ok {
      text-decoration: line-through;
      color: grey;
    }
  </style>
</head>
<body>
  <input id='inputText' placeholder="请输入代办"/>
  <button id='btn'>添加</button>
  <ul id='todoList'></ul>
  <script src='./Hello.js'></script>
</body>
</html>

todo.ts

class Todo {
  content: string; // 待办内容
  state: Boolean; // 待办状态
  constructor(content: string, state: Boolean) {
    this.content = content;
    this.state = state
  }
}

// 初始化待办信息
let todoList:Todo[] = [
  new Todo('one', true),
  new Todo('two', false)
]

const todoUlList = document.getElementById('todoList')
var textContent:HTMLInputElement = document.querySelector('#inputText')
var btn = document.getElementById('btn')

// 渲染待办列表
function renderList () {
  let list = ''
  if (todoList.length > 0) {
    todoList.forEach((item, index) => {
      list += `<li class="${item.state ? 'item-ok': ''}">${item.content}</li>`
    })
  } else {
    list = '<li>暂无待办</li>'
  }
  todoUlList.innerHTML = list
}

// 添加代办
function addTodo() {
  var text = textContent.value;
  if (text === '') {
    return 
  }
  todoList.push( new Todo(text, false))
  textContent.value = '' // 把input框清空
  renderList() // push之后重新渲染一下
}

btn.onclick = function () {
  addTodo()
}

window.onload = function() {
  renderList()
}

然后 tsc todo.ts, 转成js即可使用~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值