有没有办法添加侦听器或将事件绑定到值而不是html元素?
因此,当值更改而不是单击按钮等时会触发事件...
假设代码:
var changingValue = 1;
$('button').on('click',function(){
changingValue = changingValue + 1;
});
$(changingValue).on('change',function(){
alert("event triggered, the new value is:" + this)
});
答案 0 :(得分:1)
如果您使用这样的对象,则可以:
function Changing(initialValue, valueListener) {
this._value = initialValue;
this._listener = valueListener;
}
Object.defineProperties(Changing.prototype, {
value: {
get: function() {
return this._value;
},
set: function(value) {
this._value = value;
this._listener(this._value);
}
}
});
然后你可以这样做:
var changingValue = new Changing(1, function(value) {
alert("event triggered, the new value is: " + value);
});
$('button').on('click',function(){
changingValue.value += 1; // will alert "event triggered, the new value is: ..."
});