通过Object.defineProperty实现效果
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<input type="text" id="input-box">
<h1></h1>
<script>
let inputElement = document.querySelector('#input-box');
let h1Element = document.querySelector('h1');
let Obj = {};
Object.defineProperty(Obj,'txt',{
set:function(value){
h1Element.innerHTML = value
}
})
inputElement.oninput = function(){
Obj.txt = this.value
}
</script>
</body>
</html>
使用ES6 class实现数据双向绑定
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<input type="text" id="input-box">
<h1></h1>
<script>
let inputElement = document.querySelector('#input-box');
let h1Element = document.querySelector('h1');
class Obj {
set txt(value){ //通过setter设置txt方法
h1Element.innerHTML = value
}
}
let watcher = new Obj(); //创建一个实例,赋值给watcher
inputElement.oninput = function(){
watcher.txt = this.value
}
</script>
</body>
</html>