如何选择jQuery下拉val()并触发事件? [英] How to select jQuery drop down val() AND trigger the event?

查看:99
本文介绍了如何选择jQuery下拉val()并触发事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这样的下拉菜单中注册了一个jQuery插件:

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

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

我正在手动选择下拉菜单,如下所示:

I am manually selecting the drop down like this:

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

但是onchange事件不会触发在其之前注册的.linkToStates().因此,看起来val()仅更改下拉位置,而实际上不更改onchange事件.有人可以帮忙吗?

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?

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

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;
        }
      });
    }
  });

推荐答案

尝试一下:

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

甚至

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

您可以在.trigger() 此处.change() 查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆