使用 Javascript/jQuery 以编程方式关闭 SELECT 下拉列表

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

Close a SELECT dropdown list programmatically with Javascript/jQuery

javascriptjqueryhtmlhtml-select

提问by vtortola

I have a dropdown that is initialized with one single value. When the user clicks it, the single element is removed and a new element is added saying "Loading", then an AJAX call is issued to the server and when returns, the new values are added to the control.

我有一个用一个值初始化的下拉列表。当用户单击它时,单个元素被删除并添加一个新元素,表示“正在加载”,然后向服务器发出 AJAX 调用,当返回时,新值被添加到控件中。

The problem is that the control remains open while updating, and I would like to close it.

问题是控件在更新时保持打开状态,我想关闭它。

This is an example: http://jsfiddle.net/vtortola/CGuBk/2/

这是一个例子:http: //jsfiddle.net/vtortola/CGuBk/2/

The example's AJAX does not get data probably because something wrong I am doing when calling the jsfiddle api, but it shows how the SELECTremains open during update.

该示例的 AJAX 没有获取数据可能是因为我在调用 jsfiddle api 时做错了什么,但它显示了SELECT更新期间如何保持打开状态。

I want to know how to close the dropdown list programmatically w/o focus in another input.

我想知道如何在没有焦点的情况下以编程方式关闭另一个输入的下拉列表。

采纳答案by Death

I'm not sure about anyone else, but I'm using the latest stable build of Chrome, and none of the other answers involving .blur()work for me.

我不确定其他人,但我使用的是 Chrome 的最新稳定版本,没有其他答案涉及.blur()我的工作。

This question asks the inverse: Programmatically open a drop-down menu

这个问题反问:以编程方式打开一个下拉菜单

The conclusion that seemed to be obtained is that it's not possible due to the way the browser handles field element clicks.

似乎得到的结论是,由于浏览器处理字段元素点击的方式,这是不可能的。

A better solution would be to replace the dropdown with a pure HTML one and hide it when needed with a simple .hide()command.

更好的解决方案是用纯 HTML 替换下拉列表,并在需要时使用简单.hide()命令隐藏它。

回答by thecodeparadox

Just add this line end of your close within click.

只需在click.

$(this).blur();  

So it will look like

所以它看起来像

$select.click(function(e){

    $select.html('<option value="-1">Loading</option>');

    $(this).blur();
    ......
    ...
});

DEMO

演示

HAH ! If we have an issue with Chromenew version then:

哈!如果我们对Chrome新版本有问题,那么:

Take a fake selectlike following:

假装select如下:

<select class="fake" style="display: none">
    <option value="-1">Loading</option>
</select>

and do something like:

并执行以下操作:

$select.click(function(e) {
    $(this).hide(0); // hide current select box

    //$select.html('<option value="-1">Loading</option>');

    $('select.fake').show(0); // show the fake slide

    $.ajax({
           // your code
        }).done(function(data) {

           $('select.fake').hide(0);
           $select.show(0);

        })
        ......
    }):

DEMO

演示

回答by freefaller

After...

后...

$select.html('<option value="-1">Loading</option>');

Try adding...

尝试添加...

$select.blur();

回答by Huangism

I think all you need to do is target something else or should I say lose focus on the select (blur it)

我认为你需要做的就是瞄准别的东西,或者我应该说失去对选择的关注(模糊它)

<select>
    <option value="0">Initial Value</option>
</select>

var $select = $('select');
$select.click(function(e){

    $select.html('<option value="-1">Loading</option>');

    $.ajax({
        url: '/echo/json/',
        method:'post',
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        data: { json: JSON.stringify([1, 2, 3]), delay:1 }
    }).done(function(data){

        $.each($.map(data, function (item, i) {
                    return "<option value='" + item +"' >" + item + "</option>";

                }), function (i, item) {
                    $element.append(item);
                });

    }).fail(function(){
        alert('error');
    });

   e.preventDefault();
   e.stopPropagation(); 
   $(this).blur();    
});

回答by Jonathan

I know this is an old question and already have an answer but I think the following solution can be a fair way to achieve the goal.

我知道这是一个老问题并且已经有了答案,但我认为以下解决方案是实现目标的公平方法。

You can simulate the closure of the select by re-rendering it. In jQuery you can implement a simple plugin to achieve that:

您可以通过重新渲染来模拟选择的关闭。在 jQuery 中,您可以实现一个简单的插件来实现:

$.fn.closeSelect = function() {
    if($(this).is("select")){
        var fakeSelect = $(this).clone();
        $(this).replaceWith(fakeSelect);
    }
};

and use it this way:

并以这种方式使用它:

$("#mySelect").closeSelect();

回答by Misaz

SOLUTION 1I found very easy solution.

解决方案 1我找到了非常简单的解决方案。

select.style.display = "none";
setTimeout(function () {
    select.style.display = "block";
}, 10);

This hide element in DOM, this cause that dropdown will be closed and then with 10ms delay (without delay it does not work) return it into DOM.

这个隐藏在 DOM 中的元素,这会导致下拉列表将被关闭,然后延迟 10 毫秒(没有延迟它不起作用)将其返回到 DOM。

SOLUTION 2: Little bit more complicated but without delay is totaly remove element from DOM and then immediately return it back.

解决方案 2:稍微复杂一点,但毫不拖延地从 DOM 中完全删除元素,然后立即将其返回。

var parent = select.parentElement;
var anchor = document.createElement("div");
parent.insertBefore(anchor, select);
parent.removeChild(select);
parent.insertBefore(select, anchor);
parent.removeChild(anchor);

This stores parrent of element, then bring anchor before select. Anchor is there for restoring select in the same position in DOM then before. Of course it can be implemented to function select element.

这存储元素的父级,然后在选择之前带上锚点。锚点用于在 DOM 中与之前相同的位置恢复选择。当然,它可以实现功能选择元素。

HTMLSelectElement.prototype.closeDropdown = function () {
    var parent = this.parentElement;
    var anchor = document.createElement("div");
    parent.insertBefore(anchor, this);
    parent.removeChild(this);
    parent.insertBefore(this, anchor);
    parent.removeChild(anchor);
}

and then just call

然后就打电话

select.closeDropdown();

Example

例子

回答by Bogdan Chernovol

The easiest way I found to close a selected element is to disable it temporarily:

我发现关闭选定元素的最简单方法是暂时禁用它:

$selectElement.attr('disabled', true);

setTimeout(() => {
   $selectElement.attr('disabled', false);
}, 4);

回答by panser

$('.select').on('change', function () {
    $(this).click();
});

回答by user3619165

Old post I know but I have a very simple solution.

我知道旧帖子,但我有一个非常简单的解决方案。

$(someSelectElement).on('change', function(e) {
    e.target.size = 0    
}

That will collapse the select element if you click on any item in the list.

如果您单击列表中的任何项目,这将折叠选择元素。

回答by Vern Jensen

In case anyone else out there is using Angular2, the solution that worked there for me was to add a (focus) event that calls $($event.srcElement).attr("disabled","disabled");

如果其他人在使用 Angular2,那么对我有用的解决方案是添加一个(焦点)事件,该事件调用 $($event.srcElement).attr("disabled","disabled");

I then add a timeout to re-enable the element when I want it to become active again.

然后,当我希望它再次变为活动状态时,我添加一个超时以重新启用该元素。