使用js實現一個簡單的數據雙向綁定


實現代碼:

<input type="text" id="foo">
<button id="btn">提交</button>
<button id="btn1">設置</button>
<div>輸入框的內容:<input type="text" id="xianshi"></div>
<script>
    var user = {};
    var foo = document.getElementById("foo");
    var xianshi = document.getElementById("xianshi");
    Object.defineProperty(user, 'name', {
        get: function () {
            return document.getElementById('foo').value;
        },
        set: function (newValue) {
            console.log(newValue);
            document.getElementById('foo').value = newValue;
        },
        configurable: true
    });
    foo.oninput = function () {
        xianshi.value = user.name;
    }
    xianshi.oninput = function () {
        user.name = xianshi.value;
        xianshi.innerHTML = user.name;
    }
</script>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM