检查数组元素之一的道具 jquery

Check prop of one of the elements of the array jquery

选中输入字段后,我打开了导航的两个主要元素。 仅当打开两个手动导航元素之一时,我才尝试在 keyup esc 上触发关闭导航功能:

$(document).on('keyup', this.onPressEsc.bind(this));

onPressEsc(e) {
    if (e.keyCode === 27 && this.$body.find(selectors.input).prop('checked') === true) {
        this.closeMainNav();
        this.removeOverlay();
    }
}

当前的实现只检查数组的第一个元素,有没有办法验证这两个元素?

onPressEsc(e) {
    if (e.keyCode === 27 && this.$body.find(selectors.input).prop('checked').length === 2) {
        this.closeMainNav();
        this.removeOverlay();
    }
}

The .prop() method gets the property value for only the first element in the matched set.

所以,您 prop() 的使用不正确。如果两个元素都被选中,那只会 return 第一个元素为真。

向select匹配selectors.input的所有被检查的元素(假设这是一个带有select或定义的字符串),添加“:checked”,并测试长度:

onPressEsc(e) {
    if (e.keyCode === 27 && this.$body.find(selectors.input + ":checked").length == 2) {
        this.closeMainNav();
        this.removeOverlay();
    }
}