Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
535 views
in Technique[技术] by (71.8m points)

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

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?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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"))


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...