【问题标题】:Select2 trigger("change") creates an infinite loopSelect2 trigger("change") 创建一个无限循环
【发布时间】:2016-08-25 14:12:54
【问题描述】:

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

$('#id1').val('xyz').trigger('change');

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

$('#id1').val('xyz').trigger('change.select2')

【问题讨论】:

  • 您好,您可以在代码上按 Ctrl + K 进行格式化吗?在代码和句子之间添加空格也会很好。谢谢
  • $('#id1').val('xyz').trigger('change.select2'); 为我工作

标签: javascript jquery select2


【解决方案1】:

为避免无限循环,请使用触发方法参数 为了区分事件调用,在触发方法使用添加参数和事件回调中检查参数是否存在,当参数存在时表示事件是从代码触发的,如果不存在则表示是来自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);  
<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】:

    我在我的案例中创建了一个守卫功能。我使用了事件对象并检查了未定义。当未定义时,我知道它的代码,所以我只是退出该函数。这样,您可以在初始点击时运行代码,然后忽略人工代码。

    $("#id1").on('change',function(e){
       if(e.originalEvent === undefined)return;//bail out if code caused it
     //do stuff here
    });
    

    【讨论】:

    • 这是一个有用的答案!
    【解决方案3】:

    this answer 中,我们看到这不是设置select2 值的方法,但是:

    $('#id1').select2("val", "xyz");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-01-24
      • 2017-09-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-20
      相关资源
      最近更新 更多