實施change
事件的隱藏字段的唯一方法是通過髒檢查,如:
(function() {
var myHidden = document.getElementById('myInputHidden'),
currentValue = myHidden.value;
setTimeout(function myHiddenOnChange() {
if (myHidden.value !== currentValue) {
currentValue = myHidden.value;
myHiddenChanged.call(myHidden);
}
setTimeout(myHiddenOnChange, 30);
}, 30);
function myHiddenChanged() {
// that's your hidden field's 'change' event
}
})();
我不建議這樣做,但另一種方法是重寫在HTMLInputElement.prototype
描述:
(function() {
var _htmlInputElementValue = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value'),
_htmlInputElementValueSet = _htmlInputElementValue.set,
_ev = document.createEvent('Event');
_ev.initEvent('change', true, true);
_htmlInputElementValue.set = function() {
_htmlInputElementValueSet.apply(this, [].slice.call(arguments));
if (this.type === 'hidden') {
this.dispatchEvent(_ev);
}
}
Object.defineProperty(HTMLInputElement.prototype, 'value', _htmlInputElementValue);
})();
做的是,只要有人改變了value
隱藏字段的屬性,它會觸發change
事件,因此,如果您正在收聽該事件,那麼您的代碼將開始工作。
我沒有看到代碼的第二部分不起作用,爲什麼你認爲它不? –