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即可使用~