当我不知道jQuery的变化时刻时,触发隐藏字段的变化事件

Trigger change event on hidden field when i don't know the moment of change with jQuery?

本文关键字:变化 隐藏 事件 字段 我不知道 jQuery 时刻      更新时间:2023-09-26

我有一个隐藏的输入在我的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事件,所以,如果你正在听那个事件,你的代码将开始工作