很简单的10行代码就可以实现输入框与页面实时显示的绑定,也就是百度一下一大堆的所谓的双向数据绑定,完全没有必要搞那么长
function test() {
const container = document.createElement('div');
const inputBar = document.createElement('input');
container.appendChild(inputBar);
const textBar = document.createElement('div');
container.appendChild(textBar);
inputBar.addEventListener('input', () => textBar.innerHTML = inputBar.value);
return container;
}
document.body.appendChild(test());
创建一个test.html试一试:
<html>
<head>
<meta charset="UTF-8">
<title>two-way-binding</title>
</head>
<body>
</body>
<script>
function test() {
const container = document.createElement('div');
const inputBar = document.createElement('input');
container.appendChild(inputBar);
const textBar = document.createElement('div');
container.appendChild(textBar);
inputBar.addEventListener('input', () => textBar.innerHTML = inputBar.value);
return container;
}
document.body.appendChild(test());
</script>
</html>
演示结果如下: