简单的原生js实现双向绑定!
作者:互联网
一直以来都没时间看双向绑定是什么原理,今天特意写一下原生js实现双向绑定:附上代码如下
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>双向绑定</title> </head> <style> </style> <body> <input type="text" model="inputvalue1"> <input type="text" model="inputvalue2"> <input type="text" model="inputvalue3"> <div id="text"></div> </body> <script> // const input = document.querySelector('input[model]') const ngmodel = { inputvalue1: "初始1", inputvalue2: "初始2", inputvalue3: "初始3" }; // 初始化赋值 const inputs = document.querySelectorAll('input[model]'); for (let i = 0; i < inputs.length; i++) { inputs[i].value = ngmodel[inputs[i].getAttribute('model')] inputs[i].addEventListener('keyup', change) }; document.getElementById('text').innerHTML = "我是初始值"; // input操作赋值 function change(e) { const attr = e.target.getAttribute('model'); ngmodel[attr] = e.target.value document.getElementById('text').innerHTML = ngmodel[attr]; } </script> </html>
标签:原生,inputs,ngmodel,const,绑定,js,input,model,document 来源: https://www.cnblogs.com/smileCJ521/p/10623773.html