OnChange -当shift或control键按下时暂停功能

OnChange - Pause function if shift or control key is down

本文关键字:暂停 功能 control shift OnChange      更新时间:2023-09-26

我使用下面的函数来填充一些组合框。

<script type="text/javascript">
function getcompany() {
    $.post('filters.php', 
       $('form[name="report1"]').serialize(), 
       function (output) {
       var options = output.split(',');
           $('#M1').html(options[0]).show();
           $('#T1').html(options[1]).show();
           $('#I1').html(options[2]).show();
           $('#C1').html(options[3]).show();
       });
}
</script>

这是由OnChange事件触发的,如果用户只想通过组合框中的一个项目进行过滤,则可以正常工作。但是,如果使用Control或Shift键选择多个项目,则在选择下一个项目之前,选项会发生变化。所以,我需要的是一种方法来检测这些键中的任何一个是down,暂停函数,然后在键被释放后恢复它。

又尝试了一天之后,我想到了这个。还增加了shift键。

<script type="text/javascript">
//Set default variable to no
downkey = "No";
//Set variable to yes if key(s) are down
$(document).keydown(function(down){
if(down.keyCode == 16 || down.keyCode == 17) {
downkey = "Yes";
}
});
//Return variable to no and call the function when the key(s) are released
$(document).keyup(function(up){
if(up.keyCode == 16 || up.keyCode == 17) {
downkey = "No";
getcompany(); 
}
});
</script>
<script type="text/javascript">
function getcompany() {
if(downkey == "No"){//Checks the downkey variable to see if it is currently set to Yes or No
    $.post('filters.php', 
       $('form[name="report1"]').serialize(), 
        function (output) {
        var options = output.split(',');
            $('#M1').html(options[0]).show();
            $('#T1').html(options[1]).show();
            $('#I1').html(options[2]).show();
            $('#C1').html(options[3]).show();
       });
}
}
</script>

我还没有对此进行测试,但是您可以使用事件对象确定是否按下了控制键。e.ctrlKey

button.onclick = function (e) {
    if (e.ctrlKey) {
       //  do nothing
    }else {
       getCompany();
    }
}

同样适用于shift键e.shiftKey

button.onclick = function (e) {
    if (e.ctrlKey || e.shiftKey) {
       //  do nothing
    }else {
       getCompany();
    }
}