【问题标题】:jQuery fire event if input is changed through Javascript如果通过 Javascript 更改输入,则 jQuery 触发事件
【发布时间】:2015-05-30 10:26:15
【问题描述】:

如果输入文本已通过 Javascript 使用 .val() 更改,我需要触发一个事件,来自 jQuery API (https://api.jquery.com/change/):Note: Changing the value of an input element using JavaScript, using .val() for example, won't fire the event.

已经尝试过How can I trigger an onchange event manually?,但似乎不起作用...

这是我的代码:

<input type="text" id="datePrint" maxlength="10" size="6" disabled>
<img src="scripts/calendar/calendar.png" id="datePick" border="0" align="absmiddle" alt="Pick Date" width="40px" height="40px">

JS:需要激活日历事件

Calendar.setup({inputField:'datePrint',ifFormat:'%d/%m/%Y',button:'datePick',align:'T1',singleClick:true}); 

这是日历JS:

http://www.mediafire.com/view/yfrls2nx4m6ls52/calendarJs.txt

【问题讨论】:

标签: javascript jquery onchange


【解决方案1】:

您始终可以在更改输入值时触发change 事件。

$("input#id").trigger('change');

【讨论】:

  • 无法触发,因为生成的输入文本来自日历 JS。
  • 那么日历 JS 必须有一个 API,它可以帮助您跟踪何时将文本放置在输入字段中。您可以在此处自行触发更改。你能发布你的代码吗?
  • 代码已发布...我很难阅读日历js代码,我没有太多时间:S
【解决方案2】:

有两种方法。简单的答案是记住,每次使用.val() 时也要调用.change()

但是,这引出了一个问题,即 DOM 是否是保存状态信息的最佳位置。一个更复杂但更灵活的解决方案是创建一个 model/view 对象来存储状态并让它管理事件和更新。

但是,在对 cme​​ts 进行进一步检查后,您尝试解决的实际问题不是如何触发更改事件,而是如何在另一个第三方库实际更改输入时判断输入何时更改。

第一步是调查相关库,看看它们是否提供了可以附加到的更改事件。如果不是(在考虑了其他性能更好的库之后),您可能会被轮询解决方案所困。

function InputChangePoller(selector) {
  this.el = $(selector);
  this._lastKnownValue = this.el.val();
}

InputChangePoller.prototype.start = function() {
  this._timmer = setImmediate($.proxy(this, 'checkValue'), 10);
  return this;
};

InputChangePoller.prototype.stop = function() {
  clearImmediate(this._timmer);
  return this;
};

InputChangePoller.prototype.checkValue = function() {
  var value = this.el.val();
  if (value !== this._lastKnownValue) {
    this._lastKnownValue = value;
    this.el.trigger('change', value);
  }
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多