简体   繁体   English

select2-清除按类别定位时所有无效的项目

[英]select2 - clear all items not working when targeting by class

I have a select2 combobox, from which I want to clear out all items. 我有一个select2组合框,我想从中清除所有项目。

If I target the select with an ID, then it works: 如果我使用ID定位选择,那么它可以工作:

$("#clearId").click(function(){
  $("#list").empty();
});

However, if I target the select with a class, it actually removes the select from the dom: 但是,如果我将选择与某个类作为目标,则实际上会将选择从dom中删除:

$("#clearClass").click(function(){
    $(".list").empty();
});

This can be seen in the following demo: http://jsfiddle.net/NvrZu/ 可以在以下演示中看到: http : //jsfiddle.net/NvrZu/

I need to be able to target the select via a class. 我需要能够通过类来定位选择。

The dynamically added parent of the select also gets the .list class when the plugin wraps the original select, so you're not just removing the options in the select, but the select as well, as you're emptying the parent element. 当插件包装原始的select时,动态添加的select的父对象也会获得.list类,因此,在清空父元素时,您不仅要删除select中的选项,还要删除select。

Excluding the wrapper added by the plugin should solve that problem : 排除插件添加的包装器可以解决该问题:

$("#clearClass").click(function(){
    $(".list").not('.select2-container').empty();
});

FIDDLE 小提琴

                $("#list").empty();
                $("#list").select2('data', null);

http://jsfiddle.net/mohammadAdil/NvrZu/1/ http://jsfiddle.net/mohammadAdil/NvrZu/1/

$("#clearClass").click(function(){
     $("select.list").empty();
});

You do have other element with class .list that you don't want to empty 您确实不想将类.list中的其他元素清空

this is div generated by plugin with class list - 这是由带有类列表的插件生成的div-

<div class="select2-container list"

See On console --> http://jsfiddle.net/mohammadAdil/NvrZu/4/ 请参阅在控制台上-> http://jsfiddle.net/mohammadAdil/NvrZu/4/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM