简体   繁体   English

在jQuery中组合多个选择器

[英]Combining multiple selectors in jQuery

I'm trying to find a solution to make this code cleaner: 我正在尝试找到一种解决方案,以使此代码更简洁:

$(document).keypress(function(ev){
         if($("#dialog").is(':visible') === false && $("#alertDialog").is(':visible') === false){
            if(ev.keyCode=='13' && !$('#resetBtn').is(':focus') && !$('.edit-new').is(':focus') && !$('.edit-trash').is(':focus')){
                return validateForm('valueTable');
            } 
            if(ev.keyCode=='27'){
                $('#resetBtn').click();
            }
         }
     });

As you can see, I'm checking to see if three seperate inputs are not in foucs before exectuing my event. 如您所见,我正在检查执行事件之前是否没有三个单独的输入。 Is there a way to target #resetBtn, .edit-new, .edit-trash into one, nicely packed selector? 有没有一种方法可以将#resetBtn,.edit-new,.edit-trash定向到一个打包好的选择器中?

Would this do what you want? 这会做你想要的吗?

$('#resetBtn:focus, .edit-new:focus, .edit-trash:focus').length === 0

You could use a similar statement for your visibility checks too. 您也可以使用类似的语句进行可见性检查。

是的,就像这样$('#resetBtn, .edit-new, .edit-trash') :)

You could use single selectors and simply check the length of their returned elements. 您可以使用单个选择器,只需检查它们返回的元素的长度即可。 No reason to explicitly check for equality with false when we can check the length property instead: 当我们可以检查length属性时,没有理由显式地检查是否为false

// Handle the keypress event on the document object
$(document).on("keypress", function (event) {
    // Proceed if no visible dialogs
    if (!$("#dialog:visible, #alertDialog:visible").length) {
        // Checking which key was pressed
        switch (event.which) {
            case 13:
                // If no focus is on #resetBtn, .edit-new, or .edit-trash
                if (!$("#resetBtn:focus, .edit-new:focus, .edit-trash:focus").length) {
                    return validateForm("valueTable");
                }
                break;
            case 27:
                // Trigger the click event on #resetBtn
                $("#resetBtn").trigger("click");
        }
    }
});

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

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