问题
Let say there are two select2 elements on the page, both using the 'onChange'. In order to programmatically set a value in one select2 element you use
$('#id1').val('xyz').trigger('change');
If when you make a selection in one of these two elements you want to reset the other to the initial value, the onChange event is triggered by the value setting and the system enters an infinite loop. The same happens if you use
$('#id1').val('xyz').trigger('change.select2')
回答1:
To avoid inifinite loop use trigger method parameters to distinguish event calls, in trigger method usage add parameter and in event callback check if paramater exists, when parameter exists that means that event was triggered from code, if no, that means it is event from ui.
Check how it works on this code example.
$(function(){
$('#id1').on("change",function(e, state){
//we check state if exists and is true then event was triggered
if (typeof state!='undefined' && state){
console.log('change #1 is triggered from code');
return false;
}
console.log('change #1 is from ui');
});
$('#id2').on("change",function(e, state){
//we check state if exists and is true then event was triggered
if (typeof state!='undefined' && state){
console.log('change #2 is triggered from code');
return false;
}
console.log('change #2 is from ui');
});
});
/**TEST CODE TO TRIGGER CHECK **/
setTimeout(function(){
$('#id1').val('1').trigger('change',[true]); //here is paramater - [true]
$('#id2').val('2').trigger('change',[true]);//here is paramater - [true]
$('#id1').val('3').trigger('change',[true]); //here is paramater - [true]
$('#id2').val('3').trigger('change',[true]);//here is paramater - [true]
},1000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span>Select 1</span>
<select id="id1">
<option val="1" >1</option>
<option val="2" >2</option>
<option val="3" >3</option>
</select>
<span>Select 2</span>
<select id="id2">
<option val="1" >1</option>
<option val="2" >2</option>
<option val="3" >3</option>
</select>
回答2:
I created a guard function in my case. I used the event object and checked for undefined. When undefined I know its code so I just bail out of the function. That way you can run the code on initial click then the artificial ones get ignored.
$("#id1").on('change',function(e){
if(e.originalEvent === undefined)return;//bail out if code caused it
//do stuff here
});
回答3:
In this answer we see that is not the way to set a select2
value, but:
$('#id1').select2("val", "xyz");
来源:https://stackoverflow.com/questions/39147672/select2-triggerchange-creates-an-infinite-loop