HTML
<input id="testinput" type="text"></input>
JS
$('#testinput').change(function (){
change();
});
function change(){
alert();
}
$('#testinput').val('new val');
Link
通过键入输入并失去焦点,它可以工作,但如果输入字段的更改是由 jquery
触发的,则它不起作用。
$('#testinput').val('new val').trigger('change'); 不需要。
最佳答案
来自MDN (由我加粗):
The change event is fired for input, select, and textarea elements when a change to the element's value is committed by the user. Unlike the input event, the change event is not necessarily fired for each change to an element's value.
如果您要以编程方式更改值,则需要手动触发 change
事件。
我想,如果您执意不手动触发更改事件,您可以重写 jQuery 的 val
($.fn.val
) 方法来为您执行此操作:
var originalVal = $.fn.val;
$.fn.val = function() {
if(arguments.length) {
originalVal.apply(this, arguments);
this.trigger('change');
return this;
}
return originalVal.call(this);
}
关于javascript - 以编程方式更改输入字段中的值执行某些任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30367895/