zoukankan      html  css  js  c++  java
  • JS 双向数据绑定、单项数据绑定

    简单的双向数据绑定

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
    <input type="text" id="aa"/>
    <span id="bb" style="border: 2px solid orange;margin-left: 20px;">{{hello}}</span>
    <br>
    <br>
    <input type="text" id="cc"/>
    
    <script>
        // 双向数据绑定的原理:属性拦截
        // 属性拦截实现方式 : 使用Object.defineProperty()将对象的属性变成访问器属性。
    
        var obj = {};
        Object.defineProperty(obj, 'hello', {
            enumerable: true,
            configurable: true,
            get: function () { // 拿到最新的值
                return document.getElementById('aa').value;
            },
            set: function (val) { // 设置最新的值
                document.getElementById('bb').innerHTML = obj.hello;
                document.getElementById('cc').value = obj.hello;
            }
        });
        Object.defineProperty(obj, 'hello2', {
            enumerable: true,
            configurable: true,
            get: function () {
                return document.getElementById('cc').value;
            },
            set: function (val) {
                document.getElementById('aa').value = obj.hello2;
                document.getElementById('bb').innerHTML = obj.hello2;
            }
        });
        document.getElementById('aa').onkeyup = function () {
            obj.hello = this.value;
        };
        document.getElementById('cc').onkeyup = function () {
            obj.hello2 = this.value;
        };
        obj.hello = ""; //属性名必须设置为空,否则在使用插值表达式的时候直接会把插值表达式显示出来
        obj.hello2 = ""; //属性名必须设置为空,否则在使用插值表达式的时候直接会把插值表达式显示出来
    </script>
    </body>
    </html>

    单项数据绑定

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
    <input type="text" id="aa"/>
    <span id="bb" style="border: 2px solid orange;margin-left: 20px;">{{hello}}</span>
    
    <script>
        // 双向数据绑定的原理:属性拦截
        // 属性拦截实现方式 : 使用Object.defineProperty()将对象的属性变成访问器属性。
    
        var obj = {};
        Object.defineProperty(obj, 'hello', {
            enumerable: true,
            configurable: true,
            get: function () {
                return document.getElementById('aa').value;
            },
            set: function (val) {
                document.getElementById('bb').innerHTML = obj.hello;
            }
        });
    
        document.getElementById('aa').onkeyup = function () {
            obj.hello = this.value;
        };
    
        obj.hello = ""; //属性名必须设置为空,否则在使用插值表达式的时候直接会把插值表达式显示出来
    </script>
    </body>
    </html>
  • 相关阅读:
    expect简介和使用例子(转)
    openshift网络
    openstack相关
    SDN的开源方案sonic
    OpenStack Neutron ML2 Deep Dive
    2017双11技术揭秘—阿里数据库计算存储分离与离在线混布
    es的gui工具
    django orm中blank和null的区别
    断关联多表关系阐述
    视图使用
  • 原文地址:https://www.cnblogs.com/haohaogan/p/15700295.html
Copyright © 2011-2022 走看看