我只是想了解纯JavaScript中的数据绑定。当我创建一个输入并附加一个事件监听器(如'input'),然后调用一个函数来替换div的innerHTML并使用该新输入值时,div将在我输入时镜像输入框。
我试图让输入框的值在没有人输入的情况下更改时更新div。因此,如果输入因某些代码而改变:
ini_set("error_reporting", E_ALL & ~E_DEPRECATED);
而不是直接在其中键入的人,我希望div中的文本仍然反映它。
我尝试使用'change'事件监听器,但只有当输入框失去焦点时才能使用它。所以我尝试将其添加到代码中:
inp.value = 'Testing'
但这也不起作用。
这是我的jsfiddle的链接:
https://jsfiddle.net/mmpal78/7g0vqwgh/1/
我猜必须有办法做到这一点。感谢。
答案 0 :(得分:0)
因此,如果输入因某些代码而改变:
inp.value = 'Testing'
而不是直接在其中键入的人,我希望div中的文本仍然反映它。
您不能这样做,value
设置为MutationObserver
时不会引发任何事件,value
也不会报告任何内容。
相反,你要么
value
更改影响的任何内容)。 KO通过让您通过其“obervables”来实现这一目标。或者,value
的最新值,然后根据当前value
进行检查。 Angular 1做了类似的事情。或者,value
的代码中明确更新您知道受{{1}}影响的任何内容(但不会扩展,将忘记执行此操作)。答案 1 :(得分:0)
我想我有点迟了,但无论如何我都会发布答案。
首先,你要做的不是双向数据绑定,双向数据绑定是指如果你改变变量值,元素的值就会改变,反之亦然。
我建议您使用一个结构,以便您可以在任何您喜欢的地方使用它,这有点复杂,但请看一下这个简单的示例,该示例特定于您尝试做的事情,您可以花一点时间来扩展:的 DEMO 强>
首先创建构造函数:
var variable=function(){
this.variables={};
}
然后你创建构造函数create
,bind
,set
和get
的原型(方法)来创建一个新变量,将它绑定到一个元素,集合或者更改变量的值,最后得到变量的值:
variable.prototype.create=function(name){
this.variables[name]={
elem:'',
value:'',
event:new Event(name+'Change')
};
}
variable.prototype.bind=function(name,element){
this.variables[name].elem=document.querySelector(element);
}
variable.prototype.set=function(name,val){
this.variables[name].value=val;
this.variables[name].elem.dispatchEvent(this.variables[name].event);
}
variable.prototype.get=function(name){
return this.variables[name].value;
}
然后你创建一个结构的实例:
var binding=new variable();
创建变量并将其绑定到input元素:
binding.create('myVar');
binding.bind('myVar','.input');
然后设置一个事件监听器来更改输入值:
document.querySelector('.input').addEventListener('myVarChange',function(){
this.value=binding.get('myVar');
document.querySelector('#div1').innerHTML=binding.get('myVar');
});
然后,如果用户输入任何文本,我们将其设置为变量:
document.querySelector('.input').addEventListener('input',function(){
binding.set('myVar',this.value);
});
最后在点击按钮时更改变量的值:
document.querySelector('#btn1').addEventListener('click',function(){
binding.set('myVar','test');
});