我的 HTML 代码中有一个隐藏输入,我想知道输入值何时发生更改。
<input type="hidden" id="myInputHidden" />
我可以做这样的事情:
$('#myInputHidden').on('change', function() {
alert('triggered');
});
首先,这不起作用,在许多帖子中我读到我必须手动触发该事件。
问题是我不知道输入值何时(何地)更改,因此我无法触发该事件。
最佳答案
实现隐藏字段的 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
事件,因此,如果您正在监听该事件,您的代码将开始工作。
关于javascript - 当我不知道 jQuery 的更改时刻时,触发隐藏字段上的更改事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33158533/