原生js實現資料單向綁定

來源:互聯網
上載者:User

標籤:修改   span   訪問   target   var   https   javascrip   mozilla   ext   

Object.defineProperty()方法直接在對象上定義一個新屬性,或修改對象上的現有屬性,並返回該對象。

Object.defineProperty(obj, prop, descriptor)

參數

  obj 定義屬性的對象。
  prop要定義或修改的屬性的名稱。

  descriptor定義或修改屬性的描述符。

  傳回值 傳遞給函數的對象。
注意:資料描述符和訪問器描述符,不能同時存在(value,writable 和 get,set)

  get:函數return將被用作屬性的值。

  set:該函數將僅接收參數賦值給該屬性的新值。(在屬性改變時調用)

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<input type="text" id="aa"/>*<input type="text" id="cc"/>
<span id="bb">{{hello}}</span>

<script>
var obj = {};
Object.defineProperty(obj,‘hello‘,{
enumerable: true,
configurable: true,
get: function() { return document.getElementById(‘aa‘).value; },
set:function(val){
document.getElementById(‘bb‘).innerHTML = val*obj.hello2;
}
});
Object.defineProperty(obj,‘hello2‘,{
enumerable: true,
configurable: true,
get: function() { return document.getElementById(‘cc‘).value; },
set:function(val){
document.getElementById(‘bb‘).innerHTML = val*obj.hello;
}
});
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>

原生js實現資料單向綁定

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.