我想通过修改data对象的setter方法,来获得一个改变对象页面进行相应修改的效果。data有leftData和rightData两个属性,分别修改其setter方法。然后在控制台中输入如data.leftData = "aa";这样的语句,但始终都只会修改rightData对应的DOM,不知道为什么,请大家帮我看看,谢谢~ 代码示例如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="./MVVM.js"></script>
<title>nodeText</title>
<style>
#container div{width:100px;height:50px;}
#left{border:1px solid red;}
#right{border:1px solid green;}
</style>
</head>
<body>
<div id="container">
<div id="left"></div>
<div id="right"></div>
</div>
</body>
<script type="text/javascript">
var data = {
leftData : "left",
rightData : "right"
}
var react = {
leftData : "left",
rightData : "right"
};
window.onload = function(){
var left = document.getElementById("left");
var right = document.getElementById("right");
for(var key in data){
Object.defineProperty(data, key, {
set : function(newVal) {
if(newVal != data[key]) {
var ele = document.getElementById(react[key]);
ele.innerHTML = newVal;
}
}
})
}
}
</script>
</html>
貌似是var 的问题?
把这个改成let试试