假设页面上有两个select2元素,都使用'onChange'。为了以编程方式在一个select2元素中设置一个值,您可以使用
$('#id1').val('xyz').trigger('change');
如果当你在这两个元素中选择一个元素时,你想要将另一个元素重置为初始值,onChange事件被值设置触发,系统进入一个无限循环。如果使用
,也会发生同样的情况$('#id1').val('xyz').trigger('change.select2')
为避免无限循环使用触发方法参数为了区分事件调用,在触发器方法使用中添加参数,在事件回调中检查参数是否存在,当参数存在时意味着事件是从代码触发的,如果不存在,则意味着它是从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>
我在这里创建了一个保护函数。我使用了事件对象并检查了未定义。当未定义时,我知道它的代码,所以我就退出函数。这样你就可以在初始点击时运行代码,然后忽略人为的。
$("#id1").on('change',function(e){
if(e.originalEvent === undefined)return;//bail out if code caused it
//do stuff here
});
在这个答案中,我们看到这不是设置select2
值的方式,而是:
$('#id1').select2("val", "xyz");