Select2触发器("change")创建无限循环 [英] Select2 trigger("change") creates an infinite loop

查看:472
本文介绍了Select2触发器("change")创建无限循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设页面上有两个select2元素,都使用'onChange'. 为了以编程方式在一个select2元素中设置值,请使用

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');

如果在这两个元素之一中进行选择时想要将另一个重置为初始值,则 onChange 事件将由值设置触发,并且系统进入无限循环. 如果您使用

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

推荐答案

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

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>

这篇关于Select2触发器("change")创建无限循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆