简体   繁体   English

2如何使JavaScript函数的执行互斥?

[英]How to make 2 JavaScript function's execution mutually exclusive?

I have two select elements with several options, I chain them together so that each updates automatically when the other one changes. 我有两个带有多个选项的选择元素,我将它们链接在一起,以便每个元素在另一个元素发生更改时自动更新。

// ########### Linked Labour Select Boxes
$('body').on('change', '#labourList > li .labourerID', function() {
    var id = $(this).val();
    $(this).parent().find('.labourerName').val(id).change();
});


$('body').on('change', '#labourList > li .labourerName', function() {
    var id = $(this).val();
    $(this).parent().find('.labourerID').val(id).change();
});

At the moment one method will trigger the other one making my page a bit slow, how can i avoid that? 目前,一种方法将触发另一种,使我的页面变慢,我该如何避免呢?

I have used a flag to communicate that the change that occurred on the select is because of user of the script. 我已经使用一个标志来传达所选内容发生的更改是由于脚本用户引起的。

Check this. 检查一下。

When the user changes one select nothing is executed in second select so the change chain is broken. 当用户更改一个选择时,在第二个选择中不执行任何操作,因此更改链断开。

 var script_triggred_change = false; $("#one").change(function() { console.log("Called One"); if (script_triggred_change) return; script_triggred_change = true; $("#two").val($("#one").val()).change(); script_triggred_change = false; }); $("#two").change(function() { console.log("Called Two"); if (script_triggred_change) return; script_triggred_change = true; $("#one").val($("#two").val()).change(); script_triggred_change = false; }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <select id="one"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> </select> <select id="two"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> </select> 

Try this 尝试这个

 var once = false; $('select').on('change', function(e) { if(once) { once = false; return; } once = true; $('select').not(this).val($(this).val()).change(); }); 
 select, option { padding: 5px; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div> <select class="lab-ids"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> </select> <select class="lab-name"> <option value="1">Peter</option> <option value="2">Hans</option> <option value="3">Fritz</option> <option value="4">Sandra</option> <option value="5">Jessy</option> </select> </div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM