Is there any way to check if an element has jquery select2 already applied to it?

ⅰ亾dé卋堺 提交于 2019-11-30 00:09:20

问题


I want to apply select2 to a bunch of jquery elements on the page that all have the same class name but it looks like if i call select2() on an element that already has had a select2() called on it then it blows up. here is my code

 $('.MyDropdowns').each(function (i, obj) {
    $(obj).select2({ width: "455px" });
});

so I want something like:

 $('.MyDripdowns').each(function (i, obj) {
    if (!$(obj).HasSelect2Initiatized)
    {
        $(obj).select2({ width: "455px" });
    }
});

Does anything like this exist?


回答1:


you can check if the element has select2 attribute

$('.MyDripdowns').each(function (i, obj) {
    if (!$(obj).data('select2'))
    {
        $(obj).select2({ width: "455px" });
    }
});

EDIT

As @Fr0zenFyr said in his comment for v4.0 you can use :

if (!$(obj).hasClass("select2-hidden-accessible"))




回答2:


Working solution:

$('.MyDripdowns:not([class^="select2"])').each(function (i, obj) {
    $(obj).select2({width: "455px"});
})

Links:

  1. ^= attribute starts with selector
  2. :not selector



回答3:


Above answer is almost correct.
But it creates problem when we are adding elements dynamically on same page and applying select 2 to newly created element.
At that times selector has to be specified using not only class but also with input type. PFB reference code.

$('inputp[type="text"].MyDripdowns').each(curr_idx, curr_elem){
    //Check if select 2 is already applied or not
    if($(curr_elem).hasClass('.select2-offscreen')){
      //Select 2 is already applied to this element
    }
    else{
       //Apply Select 2 to this element 
    }
}



回答4:


You can check if Select2 operations give and error or not with try..catch. If there is an error thrown, that means that there is not Select2 in the element.

The downside is that this will still output an error in the browser console.

try {
    $(obj).select2("close")
} catch(err) {
    // No Select2 in the element
    $(obj).select2({ width: "455px" });
}


来源:https://stackoverflow.com/questions/29854022/is-there-any-way-to-check-if-an-element-has-jquery-select2-already-applied-to-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!