【问题标题】:Test for jQuery event.classList empty测试 jQuery event.classList 是否为空
【发布时间】:2012-10-09 14:59:06
【问题描述】:

我正在尝试在 jQuery 的 e.classList 上测试是否为空(如果您为其传递参数,则讨论 jQuery 传递给事件的 DOM 映射值)。

所以,我正在做一个荒谬的 JS 检查是否为空,因为我想在 e.classList.length 小于整数 1 的情况下退出函数。

奇怪,我已经试过了

if ( ( typeof newTargetClasses !== "undefined" && newTargetClasses !== null ) && newTargetClasses.length > 0 ) {

但即使e.classList 中没有项目,它也会返回true:/

$( window ).on( 'mouseenter', '.my-class', function( e ) {

    var newTargetClasses = e.toElement.classList;

    if ( ! isNaN( newTargetClasses.length ) && newTargetClasses.length > 0 ) {
        $.each( newTargetClasses, function() {
            if ( ! thePopover.has( '.' + this ).length > 0 ) {
                el.my_jquery_func('hide');
                return false;
            }
        })
    }
}

这些布尔值我错过了什么? newTargetClasses.length 在我试图检查的情况下返回一个0 的值和number 的类型

【问题讨论】:

  • 仅供参考,我对您对@dherman's answer 的编辑投了反对票,因为我觉得这是一个如此重大的变化,您真的应该将其发布为您自己问题的答案(并接受),而 支持他的回答以表扬他的贡献。

标签: javascript jquery syntax operators conditional


【解决方案1】:

classList 不是 jQuery 的东西,它是 DOM API 的东西。这也不能完全跨浏览器工作,因为根据 MDN,IE9 不支持它。

MDN ClassList

至于您的代码,您应该能够将 if 条件简化为

// classList will always be falsy in IE9 so this will never run
if (e.toElement.classList && e.toElement.classList.length ) {}.

如果你希望它是跨浏览器的,那么你可以尝试类似

if ( $.trim(e.toElement.className) ) { ... }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-02-27
    • 2018-08-10
    • 2011-09-17
    • 2011-02-15
    • 2019-01-03
    • 1970-01-01
    • 1970-01-01
    • 2015-09-03
    相关资源
    最近更新 更多