javascript 如何选择 jQuery 下拉 val() 并触发事件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5808180/
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-10-25 18:25:03  来源:igfitidea点击:

How to select jQuery drop down val() AND trigger the event?

javascriptjqueryjquery-pluginsjquery-events

提问by TruMan1

I have a jQuery plugin registered on a drop down like this:

我在下拉列表中注册了一个 jQuery 插件,如下所示:

$('#country').linkToStates('#province');

I am manually selecting the drop down like this:

我手动选择这样的下拉菜单:

$('#country').val('United States');

But the onchange event is not triggering .linkToStates() which was registered before it. So it looks like val() only changes the drop down position but doesn't actually change the onchange event. Can anyone help?

但是 onchange 事件不会触发在它之前注册的 .linkToStates() 。所以看起来 val() 只改变了下拉位置,但实际上并没有改变 onchange 事件。任何人都可以帮忙吗?

BTW, this is the code of the registered if it helps:

顺便说一句,如果有帮助,这是注册的代码:

  $.fn.extend({
        linkToStates: function(state_select_id) {
      $(this).change(function() {
        var country = $(this).attr('value');
        $(state_select_id).removeOption(/.*/);
        switch (country) {
          case 'Canada':
            $(state_select_id).addOption(canadian_provinces, false);
            break;
          case 'United States':
            $(state_select_id).addOption(us_states, false);
            break;
          default:
            $(state_select_id).addOption({ '' : 'Please select a Country'}, false);
            break;
        }
      });
    }
  });

回答by Hari Pachuveetil

Try this:

试试这个:

$('#country').val('United States').trigger('change');

or even

甚至

$('#country').val('United States').change();

You could read more about .trigger()hereand .change()here

你可以阅读更多关于.trigger()这里.change()这里

回答by Thomas Shields

You could just put your onchanged code into a separate function and then call it after you change the value.

您可以将 onchanged 代码放入单独的函数中,然后在更改值后调用它。