当< select>的值设置为0时,Change事件不会被调用.以编程方式设置 [英] Change event doesn't get called when the value of <select> is set programmatically
问题描述
通常,当用户在<select>
中选择一个项目时,会触发'change'事件.
但是,当您将与$('select').val('something')
相同的<select>
的值更改时,不会触发该事件.
Normally, when a user selects an item in a <select>
, the 'change' event gets fired.
However, when you change the value of the same <select>
with $('select').val('something')
, the event doesn't get fired.
我知道我可以做到:
$('select').val('something').trigger('change');
但这不是我要解决的问题...
I know I could do:
$('select').val('something').trigger('change');
but that's not the problem I'm trying to solve...
是否有一种方法可以使更改事件正常运行,而无需手动触发它?
Is there a way to get the change event working, without manually triggering it?
我整理了一个快速的JsFiddle来更好地解释问题,请检查一下:
I put together a quick JsFiddle to better explain the problem, check it out:
欢呼
推荐答案
这是不可能的,除非您手动触发更改功能.如果您不喜欢多次键入该代码,请扩展jQuery对象. 提琴: http://jsfiddle.net/W723K/2/
It's not possible, unless you manually trigger the change function. If you don't like typing that code several times, extend the jQuery object. Fiddle: http://jsfiddle.net/W723K/2/
(function($){
$.fn.changeVal = function(value){
return this.each(function(){
$(this).val(value).trigger('change');
});
}
})(jQuery);
//Usage:
$('select').changeVal('something');
这篇关于当< select>的值设置为0时,Change事件不会被调用.以编程方式设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!