使用一个选项在下拉菜单上触发事件onChange [英] Firing event onChange on dropdown with one option

查看:599
本文介绍了使用一个选项在下拉菜单上触发事件onChange的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个脚本,该脚本向服务器发出请求,并获取包含一些用于动态创建下拉列表的数据的json响应,在某些情况下,服务器返回一个单一值,当然,生成的下拉列表仅一种选择(如下)

I've created a scripts that makes requests to the server and gets a json response with some data that is used to create dropdown dinamically, in some cases the server returns one single value and, of course, the dropdown generated has only one option (as follow)

<div id="wrap">
    <select class="click_me">
        <option value="1">foo</option> --> this value comes from a json response.
    </select>
</div>

这是我的jQuery脚本(我认为这是不言自明的)

This is my jQuery script (I think that it is self explanatory)

$('#wrap').on('change', 'select', function() {

    var container = $('#wrap');
    var self = $(this);
    self.nextAll().remove();

    $.ajax({
      type: 'GET',
      url: 'server/stuff?id=' + self.val(),
      dataType: 'json',
      success: function(data) {
        if (data) {
          var options = self.clone().empty().appendTo(container); //clone current dropdown.
          $.each(data, function(key, value) {
            $.each(value, function(key, value) {
              options.append($("<option />").val(key).text(value)); //fill cloned element with new data
            });
          });
        } else {
          console.log('Nothing more');
        }
      }
    });


  });

如果用户使用一个选项获得下拉菜单,则上面的脚本不起作用.我认为事件onchange根本不会触发,我尝试过onclick事件,但是当用户只想打开下拉菜单时会触发.

If user gets a dropdown with one option, the script above doesn't work. I think that event onchange is not triggered at all, I tried onclick event but it fires when user just want to open the dropdown.

请给我任何建议.

谢谢

推荐答案

您可以采用以下方法来解决此问题.当单击选择列表时,如果只有一个选项,我们可以自行调用更改事件.所以尝试

You can have a workaround for this like the following way. When clicking on the select list and if it has only one option we can call the change event by our self. So try

$('#wrap').on('change', 'select', function() {
  //your stuff 
}).click(function(){
   if($('#wrap select option').length == 1) {
    $('#wrap select').change();
  }
});

正在工作的小提琴是此处.通过在下拉菜单中添加更多选项来进行测试,以确保它也可以用于多个选项.

Working fiddle is here. Test it by adding some more options to dropdown to ensure that, it is also working for more than one options.

这篇关于使用一个选项在下拉菜单上触发事件onChange的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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