Select2 trigger("change") 创建一个无限循环

Yia*_*nis 3 javascript jquery select2

假设页面上有两个 select2 元素,都使用“onChange”。为了以编程方式在您使用的一个 select2 元素中设置一个值

$('#id1').val('xyz').trigger('change');
Run Code Online (Sandbox Code Playgroud)

如果您在这两个元素中的一个元素中进行选择时希望将另一个元素重置为初始值,则该值设置会触发onChange事件,并且系统进入无限循环。如果您使用,也会发生同样的情况

$('#id1').val('xyz').trigger('change.select2')
Run Code Online (Sandbox Code Playgroud)

Mac*_*ora 8

为避免无限循环,使用触发器方法参数 来区分事件调用,在触发器方法用法中添加参数,在事件回调中检查参数是否存在,参数存在时表示事件是由代码触发的,如果不存在则表示它是来自ui的事件.

检查它如何在此代码示例上工作。

$(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);  
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)