jQuery 使用 val() 函数设置 <select> 的值时触发 change() 事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5760873/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 19:46:52  来源:igfitidea点击:

Trigger change() event when setting <select>'s value with val() function

jqueryeventstriggersonchange

提问by Goran Radulovic

What is the easiest and best way to trigger changeevent when setting the value of selectelement.

设置select元素的值时触发更改事件的最简单和最好的方法是什么。

I've expected that executing the following code

我期望执行以下代码

$('select#some').val(10);

or

或者

$('select#some').attr('value',  10);

would result in triggering the change event, which i think is pretty logic thing to be done. Right?

会导致触发更改事件,我认为这是非常合乎逻辑的事情。对?

Well, it isn't the case. You need to triger change() event by doing this

好吧,事实并非如此。您需要通过执行此操作来触发 change() 事件

$('select#some').val(10).change();

or

或者

$('select#some').val(10).trigger('change');

but i'm looking for some solution which would trigger change event as soon as select's value is changed by some javascript code.

但我正在寻找一些解决方案,一旦某些 javascript 代码更改了 select 的值,就会触发更改事件。

采纳答案by criticman

I had a very similar issue and I'm not quite sure what you're having a problem with, as your suggested code worked great for me. It immediately(a requirement of yours) triggers the following change code.

我遇到了一个非常相似的问题,我不太确定您遇到了什么问题,因为您建议的代码对我来说效果很好。它立即(您的要求)触发以下更改代码。

$('#selectField').change(function(){
    if($('#selectField').val() == 'N'){
        $('#secondaryInput').hide();
    } else {
        $('#secondaryInput').show();
}
});

Then I take the value from the database (this is used on a form for both new input and editing existing records), set it as the selected value, and add the piece I was missing to trigger the above code, ".change()".

然后我从数据库中获取值(这在表单上用于新输入和编辑现有记录),将其设置为选定值,并添加我缺少的部分以触发上述代码,“.change() ”。

$('#selectField').val(valueFromDatabase).change();

So that if the existing value from the database is 'N', it immediately hides the secondary input field in my form.

因此,如果数据库中的现有值为“N”,它会立即隐藏表单中的辅助输入字段。

回答by Dima R.

One thing that I found out (the hard way), is that you should have

我发现的一件事(艰难的方式)是你应该有

$('#selectField').change(function(){
  // some content ...
});

defined BEFORE you are using

在您使用之前定义

$('#selectField').val(10).trigger('change');

or

或者

 $('#selectField').val(10).change();

回答by Clarence Liu

The straight answer is already in a duplicate question: Why does the jquery change event not trigger when I set the value of a select using val()?

直接的答案已经在一个重复的问题中:为什么当我使用 val() 设置选择的值时,jquery 更改事件不会触发?

As you probably know setting the value of the select doesn't trigger the change() event, if you're looking for an event that is fired when an element's value has been changed through JS there isn't one.

您可能知道设置 select 的值不会触发 change() 事件,如果您正在寻找在通过 JS 更改元素值时触发的事件,则没有。

If you really want to do this I guess the only way is to write a function that checks the DOM on an interval and tracks changed values, but definitely don't do this unless you must (not sure why you ever would need to)

如果您真的想这样做,我想唯一的方法是编写一个函数来检查 DOM 的间隔并跟踪更改的值,但绝对不要这样做,除非您必须这样做(不确定为什么需要这样做)

Added this solution:
Another possible solution would be to create your own .val()wrapper function and have it trigger a custom event after setting the value through .val(), then when you use your .val() wrapper to set the value of a <select>it will trigger your custom event which you can trap and handle.

Be sure to return this, so it is chainable in jQuery fashion

添加此解决方案:
另一种可能的解决方案是创建您自己的.val()包装器函数,并在通过 设置值后触发自定义事件.val(),然后当您使用 .val() 包装器设置 a 的值时<select>,它将触发您的自定义事件您可以捕获和处理。

一定要return this,所以它可以以 jQuery 方式链接

回答by Beaumont

I separate it, and then use an identity comparison to dictate what is does next.

我将它分开,然后使用身份比较来决定接下来要做什么。

$("#selectField").change(function(){
  if(this.value === 'textValue1'){ $(".contentClass1").fadeIn(); }
  if(this.value === 'textValue2'){ $(".contentclass2").fadeIn(); }
});

回答by Mohamed23gharbi

As jQuery won't trigger native change event but only triggers its own change event. If you bind event without jQuery and then use jQuery to trigger it the callbacks you bound won't run !

因为 jQuery 不会触发本机更改事件,而只会触发它自己的更改事件。如果您在没有 jQuery 的情况下绑定事件,然后使用 jQuery 触发它,您绑定的回调将不会运行!

The solution is then like below (100% working) :

解决方案如下(100%工作):

var sortBySelect = document.querySelector("select.your-class"); 
sortBySelect.value = "new value"; 
sortBySelect.dispatchEvent(new Event("change"));