简体   繁体   中英

Select2 off('change').on('change'…) does not able to change the selected option

I use Select2-4.0.0 And

$gameSelect.select2().on("change",function(e){....}

works fine.

But when I chain it following off('change') like:

$gameSelect.select2().off('change').on("change",function(e){....}

The event is triggered but the selected item does not change at UI.

Why is that?

Looks like the select2-4.0 is adding its own change handlers to the select element, when you say off('change') that too is getting removed that is the reason.

To fix this kind of problems we have event name spacing so, use a namespace to your handlers and use it to remove them like

$('#my-select').select2().off('change.mychange').on('change.mychange', function () {
    //your code
});

Demo: Fiddle

To preserve the settings of select2 , use this code instead of the accepted solution :

$('#my-select').off('change.mychange').on('change.mychange', function () {
    //your code
});

You don't need to reinstatiate the .select2() . It's unnecessary and also shorter.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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